我希望能夠在運行時列出介面中的所有屬性,但這看起來不可能。那么我可以創建一個包含字串屬性名稱串列的介面嗎?
試過這個,但它不起作用
interface MyInterface {
prop1: string;
propsList: MyProps;
}
type MyProps = "my_prop_1" | "my_prop_2"; //these types should be string
function addProps(){
const myInterface: MyInterface = {
prop1: "hello",
propsList: {
my_prop_1: "world",
my_prop_2: "hello world"
}
}
}
嘗試使用該界面會導致
型別 {my_prop_1: string, my_prop_2: string} 不可分配給型別“MyProps”
然后,我希望以后能夠將其MyProps用作字串串列來檢查另一個串列中的屬性。
這可能嗎?
uj5u.com熱心網友回復:
使用一組屬性,以便您可以在運行時使用:
const myProps = ["my_prop_1", "my_prop_2"] as const;
然后你可以MyProps像這樣得到你的舊型別:
type MyProps = (typeof myProps)[number];
最后為您的界面使用映射型別:
interface MyInterface {
prop1: string;
propsList: {
[K in MyProps]: string;
};
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/449563.html
標籤:打字稿
上一篇:TypeScript-為什么在將陣列型別定義為number[]后無法將值推送到字串?細繩[]
下一篇:我可以宣告陣列文字的型別嗎?
