Typescript 是否可以在索引接口上添加布尔属性?
我有这样一个界面:Typescript 是否可以在索引接口上添加布尔属性?,typescript,Typescript,我有这样一个界面: interface FormState { [key: string]: string; } 当它被索引时,我需要添加一个加载指示器,所以我想添加一个布尔属性的加载,当我这样做时: interface FormState { [key: string]: string; loading: boolean } 我犯了一个错误 “boolean”类型的属性“loading”不可分配给字符串索引 键入“string” 如何为该接口添加加载道具?问题是索引签名必须与任
interface FormState {
[key: string]: string;
}
当它被索引时,我需要添加一个加载指示器,所以我想添加一个布尔属性的加载,当我这样做时:
interface FormState {
[key: string]: string;
loading: boolean
}
我犯了一个错误
“boolean”类型的属性“loading”不可分配给字符串索引
键入“string”
如何为该接口添加加载道具?问题是索引签名必须与任何命名属性兼容。一个选项是向索引签名添加
boolean
:
interface FormState {
[key: string]: string | boolean;
loading: boolean
}
另一种选择是使用交叉点。交叉点不检查交叉点成员的索引是否与交叉点中的所有特性兼容:
type FormState = {
[key: string]: string;
} & {
loading: boolean
}
尽管这种方法存在问题:
boolean
由于索引签名而不能分配给string
)“正在加载”
let f = {
loading: true
} as FormState
let v = f['loading'] // boolean
let k = 'loading' as string;
let v2 = f[k] // string