![](/img/trans.png)
[英]TypeScript: Initialize interface like array (without specifying member name)
[英]Create Interface in Typescript without specifying property name
我记得有一种方法可以在接口内创建一个字段而不指定其名称,如下所示:
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.
};
因为您已将对象的任何字符串命名属性定义为具有字符串值,所以您只能给secondProperties
一个字符串值,因为secondProperties
本身就是一个字符串。
或者考虑一下:
interface myInterface {
[propName: string]: string | boolean;
["secondProperties"]: boolean;
}
因为secondProperties
是一个字符串,并且它的值返回一个 boolean,所以它不会抛出错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.