我需要強制一個數組擁有一組特定的值,這些值應該是我的接口的鍵。 我可以強制陣列陣列類型的Typescript接口
type SomeProperties = ['prop1', 'prop2', 'prop3'];
,但我不知道如何強制接口有這些屬性。我想是這樣
type MyInterface = {
[key in keyof SomeProperties]: string;
}
但顯然數組的按鍵都只是數字,所以我的界面成爲
interface MyInterface {
0: string;
1: string;
2: string;
}
,而不是想要的界面
interface MyInterface {
prop1: string;
prop2: string;
prop3: string;
}
你知道,如果有在Typescript中實現這一點的一種方法?
這將是有用的,因爲我需要迭代一些屬性來「克隆」一個對象,我也需要輕鬆訪問這些屬性。 在類型和界面中重複屬性對我來說都有點脆弱。
嘗試將'Someofperties'鍵改爲'SomeProperties [number]'。 – jcalz
@jcalz這是一個好主意,但不幸的是它不起作用,IDE暗示了我的屬性,比如'length','at','charAt'等等,但不是'prop1','prop2'或'prop3' :( – Julo
不是'keyof SomeProperties [number]';只是'SomeProperties [number]'。 – jcalz