[英]How do I use a reference to a property in an interface as a type in TypeScript?
在我正在编写的这个应用程序中,有一个控制设置的界面; 这是它的外观示例:
export interface Config {
volume: number
graphics: string
darkMode: boolean
}
然后我有一个 class 实现它,如下所示:
import {Config} from './config'
export class DefaultConfig implements Config {
volume = 100
graphics = 'low' // I'd usually use an enum for this, but this is just an example
darkMode = false
}
最终加载到设置 class 中,如下所示:
import {DefaultConfig} from './default-config'
export abstract class Settings {
static config = new DefaultConfig()
}
所以,问题是我希望用户能够更改,例如,使用 HTML 范围输入元素的音量。 我想知道答案的问题是:如何指定一个类型,它必须是具有数字类型的 class 的属性? 例如:
import {Settings} from './settings'
import {HtmlUiElement} from './html-ui-element'
export class HtmlSettingSlider extends HtmlUiElement {
protected setting: number // What type can I put here instead?
// Code to assign, change, read from the setting goes here
}
我想分配给setting
属性,例如: Settings.config.volume
虽然“数字”在技术上有效,但它不受类型保护; 我希望它是一个带有类型号的 Config 值。 这可能吗?
你可能打算这样做
export class HtmlSettingSlider implements HtmlUiElement {
protected setting: Config[keyof Config] & number
}
现在我完全迷失了你所有的课程。 我认为您使事情过于复杂,我建议您尽可能使用普通的旧 Javascript 对象。
const defaultConfig: Config = {
volume: 100,
graphics: 'low',
darkMode:false
};
但我可能错过了一些东西
仅当您为 Settings 中的每个变量定义不同的接口时,这才有效。 像这样的东西。
export interface Volume {
value: boolean;
}
export interface Graphics {
value: string;
}
导出接口 DarkMode { 值:boolean; }
export interface Config {
volume: Volume;
graphics: Graphics;
darkMode: DarkMode;
}
现在你很安全,可以控制 go 的值的类型。然后你可以说:
setting: Volume = Settings.config.volume;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.