我有一個界面:
interface MyInterface {
field_1 : string
field_2 : string
// ... other fields with a certain number
}
我有一個 getter 函式,它接收 MyInterface 的實體,并且應該動態檢索該物件的屬性值
const myFactory = (myInstance:MyInterface):string => {
// Here some logic to retrieve a specific number
// for convenience lets say that the output of this logic is 1
let output = 1
return myInstance[`field_${output}`] // <=== This does not work since it calls a property of the interface dynmically
}
如何動態呼叫介面的屬性?
我看到了keyof操作員:但我不知道如何在這里使用它
uj5u.com熱心網友回復:
選項1:
type myKey = `field_${'1' | '2' | '3'}`
const output = '3'
const fieldKey: myKey = `field_${output}`
選項 2:
const fieldKey = `field_${output}` as keyof MyInterface
return myInstance[fieldKey]
uj5u.com熱心網友回復:
該as關鍵字只能欺騙打字稿到讓你做什么你認為你在做什么。
使用 TypeScript 3,這可能是唯一的方法。
如果您使用的是 TypeScript 4 ,則可以fieldKey使用Template Literal Type對結果進行一些驗證:
type MyField = `field_${number}`;
type MyType = Record<MyField, string>;
const myFactory = (instance: MyType): string => {
let n = 12;
const fieldName: keyof MyType = `field_${n}`;
return instance[fieldName];
}
在此代碼段中,如果您為n, (例如"x")提供了一個非數字值,那么它將屈服于"field_x"哪個被拒絕(即在編譯時被 TypeScript 檢測為不正確)。
就像你寫的一樣:
const fieldName: keyof MyType = `wrong_${n}`;
因為wrong_12在 中無效MyType。
如果您需要構建一個更大MyType的附加欄位,其形狀與 不同field_N,您可以宣告:
type LargerType = MyType & {
anotherField: string;
};
最后,如果您需要限制數量,您可以宣告:
type MyField = `field_${1 | 2 | 3 | 4}`;
在這種情況下,帶有的代碼段會n = 12產生錯誤,因為12已知被禁止。如果該n值是動態獲取的,而不是像這里那樣推斷的,則需要將其宣告為:
let n: 1|2|3|4;
(或者更有可能,您會type為接受的數字宣告 a ,因為現在您在多個地方使用它們。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/409701.html
標籤:
上一篇:使用泛型獲取嵌套型別
下一篇:在kivy中按下時洗掉一個小部件
