![](/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.