[英]Create Interface in Typescript without specifying property name
I remember there is a way to create, inside an interface, a field without specifying its name, something like this:我记得有一种方法可以在接口内创建一个字段而不指定其名称,如下所示:
export interface myInterface{
[propName:string]:string;
}
If I remember well, that sinthax means I can create a field with whatever name I want, something like this:如果我没记错的话,sinthax 意味着我可以用我想要的任何名称创建一个字段,如下所示:
ob:myInterface = {customName: "value"}
What I'm trying to do now is to add a new field to that interface, with a specific name, something like this:我现在要做的是向该界面添加一个具有特定名称的新字段,如下所示:
export interface myInterface{
[propName:string]:string;
secondProperties: boolean;
}
When I try the code above I get this error:当我尝试上面的代码时,我得到了这个错误:
Property 'secondProperties' of type 'boolean' is not assignable to string index type 'string'
What is my error?我的错误是什么?
You need to define all possible types for [propName: string]
So you need to do it in this way你需要为
[propName: string]
定义所有可能的类型所以你需要这样做
export interface myInterface{
secondProperties: boolean
[propName:string]: string | boolean;
}
I never found a good solution but the problem arises from this.我从来没有找到一个好的解决方案,但问题由此而来。
You are trying to force a property to be of type boolean & string
, which equals to never
.您试图强制属性为
boolean & string
类型,这等于never
。
type myInterface = {
[propName:string]: string;
} & {
secondProperties: boolean;
};
const obj: myInterface = {
secondProperties: true,
};
Thanks to @LaytonGB for hinting, that |
感谢@LaytonGB的提示,那
|
can be used to make almost the type we wanted.几乎可以用来制作我们想要的类型。
type myInterface = {
[propName:string]: string;
} | {
secondProperties: boolean;
};
const obj: myInterface = {
secondProperties: 'string' || true,
otherProps: 'string only', // booleans will result in error.
};
Because you have defined any string-named-property of your objects to have a value of string, you can only give secondProperties
a string value, because secondProperties
itself is a string.因为您已将对象的任何字符串命名属性定义为具有字符串值,所以您只能给
secondProperties
一个字符串值,因为secondProperties
本身就是一个字符串。
Alternatively consider this:或者考虑一下:
interface myInterface {
[propName: string]: string | boolean;
["secondProperties"]: boolean;
}
Because secondProperties
is a string, and its value returns a boolean, it is not throwing errors.因为
secondProperties
是一个字符串,并且它的值返回一个 boolean,所以它不会抛出错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.