我记得有一种方法可以在接口内创建一个字段,而无需指定其名称,类似于以下内容:
export interface myInterface{
[propName:string]:string;
}
如果我记得很清楚的话,sinthax意味着我可以用我想要的任何名称创建一个字段,比如:
ob:myInterface = {customName: "value"}
我现在要做的是在这个接口上添加一个新的字段,它有一个特定的名称,类似于:
export interface myInterface{
[propName:string]:string;
secondProperties: boolean;
}
当我尝试上面的代码时,我得到了这个错误:
Property 'secondProperties' of type 'boolean' is not assignable to string index type 'string'
我的错误是什么?
您需要为[propName: string]
定义所有可能的类型所以你需要这样做
export interface myInterface{
secondProperties: boolean
[propName:string]: string | boolean;
}
我从未找到一个好的解决方案,但问题就是由此产生的。
您正试图强制属性的类型为boolean & string
,该类型等于never
。
type myInterface = {
[propName:string]: string;
} & {
secondProperties: boolean;
};
const obj: myInterface = {
secondProperties: true,
};
操场
感谢@LaytonGB的提示,|
可以用来使几乎成为我们想要的类型。
type myInterface = {
[propName:string]: string;
} | {
secondProperties: boolean;
};
const obj: myInterface = {
secondProperties: 'string' || true,
otherProps: 'string only', // booleans will result in error.
};
因为您已经将对象的任何字符串命名属性定义为值为string,所以您只能给secondProperties
一个字符串值,因为secondProperties
本身就是一个字符串。
或者考虑一下:
interface myInterface {
[propName: string]: string | boolean;
["secondProperties"]: boolean;
}
因为secondProperties
是一个字符串,并且它的值返回布尔值,所以它不会抛出错误。