其属性仅在 TypeScript 中为类型 A 和 B 的接口?
Interface whose properties are of types A and B only in TypeScript?
我已经为我的配置创建了一个类型为 ButtonConfigs
的容器(按照建议 )。
export interface ButtonConfigs {
[key: string]: ButtonConfig;
}
我还继续使用其他组件的配置,以便每种类型在组件中都有自己的配置 属性。
...
buttonConfigs: ButtonConfigs = {};
folderConfigs: FolderConfigs = {};
txtBoxConfigs: TxtBoxConfigs = {};
...
然后我想到我应该能够将所有配置聚合到一个公共 属性。这对我来说也很有意义。
但是,我不确定是否可以通过允许不同类型的方式更改接口,仍然限制 configs
的内容不能是 any
。我目前的方法设计不佳。
export interface Configs {
[key: string]: any;
}
我如何告诉 TypeScript 字段的类型应该是 TextBoxConfig
、ButtonConfig
或 FolderConfig
而不是其他?
您尝试过使用 union type 吗?
interface ButtonConfig {
a: string;
}
interface FolderConfigs {
b: number;
}
interface TxtBoxConfigs {
c: boolean;
}
export interface Configs {
[key: string]: ButtonConfig | FolderConfigs | TxtBoxConfigs;
}
const config: Configs = {
buttonConfig: {
a: "testing"
},
folderConfig: {
b: 1
},
textConfig: {
c: true
},
anotherConfig: { // error: Type 'number' is not assignable to type 'string'.
a: 1
},
moreConfig: {
d: "test" // error: Object literal may only specify known properties, and 'd' does not exist in type 'ButtonConfig | FolderConfigs | TxtBoxConfigs'.
}
}
我已经为我的配置创建了一个类型为 ButtonConfigs
的容器(按照建议
export interface ButtonConfigs {
[key: string]: ButtonConfig;
}
我还继续使用其他组件的配置,以便每种类型在组件中都有自己的配置 属性。
...
buttonConfigs: ButtonConfigs = {};
folderConfigs: FolderConfigs = {};
txtBoxConfigs: TxtBoxConfigs = {};
...
然后我想到我应该能够将所有配置聚合到一个公共 属性。这对我来说也很有意义。
但是,我不确定是否可以通过允许不同类型的方式更改接口,仍然限制 configs
的内容不能是 any
。我目前的方法设计不佳。
export interface Configs {
[key: string]: any;
}
我如何告诉 TypeScript 字段的类型应该是 TextBoxConfig
、ButtonConfig
或 FolderConfig
而不是其他?
您尝试过使用 union type 吗?
interface ButtonConfig {
a: string;
}
interface FolderConfigs {
b: number;
}
interface TxtBoxConfigs {
c: boolean;
}
export interface Configs {
[key: string]: ButtonConfig | FolderConfigs | TxtBoxConfigs;
}
const config: Configs = {
buttonConfig: {
a: "testing"
},
folderConfig: {
b: 1
},
textConfig: {
c: true
},
anotherConfig: { // error: Type 'number' is not assignable to type 'string'.
a: 1
},
moreConfig: {
d: "test" // error: Object literal may only specify known properties, and 'd' does not exist in type 'ButtonConfig | FolderConfigs | TxtBoxConfigs'.
}
}