假設我有一個這樣的簡單代碼:
interface MyBase {
name: string;
}
interface MyInterface<T extends MyBase> {
base: MyBase;
age: number;
property: "name" // should be: "string" but only properties from T
}
const myFunc = <T extends MyBase>(item: MyInterface<T>) => {
return item.base[item.property];
}
let t:MyInterface<MyBase> = {base: {name: "Chris"}, age: 30, property: "name"};
console.log(myFunc(t)); // will log "Chris"
我正在通過 MyInterface 中的字串“property”從基類訪問屬性。這只有效,因為我只允許它準確地成為“名稱”。
我想指定 property-property 只允許表示通用物件 T 上的屬性的字串。如果我只是將其更改為“字串”,Typescript 當然會在 myFunc 中抱怨,我不想明確地轉換為任何東西。
這可能嗎?
提前問候和感謝,克里斯托夫
uj5u.com熱心網友回復:
你可以使用keyof. 我在下面稍微修改了您的代碼:
interface MyBase {
name: string;
}
interface MyInterface<T extends MyBase> {
base: T;
age: number;
property: keyof T; // should be: "string" but only properties from T
}
const myFunc = <T extends MyBase>(item: MyInterface<T>) => {
return item.base[item.property];
};
let t: MyInterface<MyBase> = {
base: { name: "Chris" },
age: 30,
property: "name",
};
console.log(myFunc(t));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/444517.html
