angular - 其属性仅在 TypeScript 中属于 A 和 B 类型的接口?
问题描述
我为我的配置创建了一个持有者,类型ButtonConfigs
如下(如this answer中所建议)。
export interface ButtonConfigs {
[key: string]: ButtonConfig;
}
我继续使用其他组件的配置,以便每种类型在组件中都有自己的配置属性。
...
buttonConfigs: ButtonConfigs = {};
folderConfigs: FolderConfigs = {};
txtBoxConfigs: TxtBoxConfigs = {};
...
然后我突然想到我应该能够将所有配置聚合到一个公共属性中。在我的情况下,这也很有意义。
但是,我不确定是否可以以允许不同类型的方式更改接口,但仍然限制configs
not to的内容any
。我目前的方法设计不佳。
export interface Configs {
[key: string]: any;
}
我如何告诉 TypeScript 该字段的类型应该是TextBoxConfig
,ButtonConfig
或者FolderConfig
没有别的?
解决方案
您是否尝试过使用联合类型?
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'.
}
}
推荐阅读
- python - SimpleItk 裁剪图像
- reactjs - 使用 setState 更新 React-Select 菜单?
- c++ - FindWindowA() 返回 0,当我使用 GetLastError() 检查错误代码时,它也是 0 (ERROR_SUCCESS)
- python - 查找包含多个名称的文件路径
- docker - docker container 创建了一个容器,但是不能运行
- c++ - 在 C++ 中对复制的数组中的元素求和
- mysql - GROUP_CONCAT 拆分在不同的列 MYSQL
- oauth-2.0 - 使用 Google OAUTH2 的 OAuth SSO 登录停止工作
- python - ipywidgets & 如何评估表单上的答案
- javascript - 如何在悬停条形图上添加“阴影”?