下面描述了我想做的事情:
interface Customer {
name: string;
age: number;
}
const getCustomer = () => {
return {
name: 'bob',
age: 42
}
}
export const getValue = (key: keyof Customer): typeof Customer[key] => {
const customer = getCustomer();
return customer[key];
};
但 TS 編譯器不喜歡這條線typeof Customer[key]。我可以做這個any或string | number,但我應該能夠從中得到型別。例如,如果我寫:
getValue('name')它回傳什么?你知道沒有任何運行時資訊,它會回傳一個string. 如果我寫getValue('age')呢?一個number當然。getValue(someInputVal as any)可能會回傳stringor number,但所有這些都在編譯時完全可用。那么 - 有沒有辦法從打字稿中得到這個?
uj5u.com熱心網友回復:
您可以稍微重寫您的函式以使用泛型:
export function getValue<T extends keyof Customer>(key: T): Customer[T] {
const customer = getCustomer();
return customer[key];
};
這本質上是說getValue應該只接受一個擴展介面鍵的引數,它將從Customer介面回傳與該T鍵關聯的型別。
這是我建議的示例解決方案的ts 操場鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/464713.html
標籤:打字稿
上一篇:通過自定義索引在表格上顯示資料
下一篇:如何在打字稿中反轉文本?
