type transaction = {
uid: string,
paymentMode : string,
}
我想從型別中獲取鍵名,例如
function getFieldName(input) {
returns a string with key name
}
const tran : transaction = {}
getKeyName(tran.paymentMode) returns 'paymentMode'
我閱讀了很多文章并嘗試了一些解決方案,所以我知道我們至少需要為該型別創建物件,這很好。
我想這樣做是因為需要型別的鍵名,并且我還想在我們鍵入類似內容obj.key以避免錯誤時保持鍵名的自動完成。
我知道,我可以使用常量鍵值對從型別創建一個單獨的物件。我想避免這種情況,因為只要型別發生變化,我們就需要在 2 個地方更改相同的內容,這可能會被忽略。
編輯:
我正在尋找這個 - 
TS游樂場
type Transaction = {
uid: string;
paymentMode: string;
};
function getFieldName <T extends object, K extends keyof T>(o: T, key: K): K {
return key;
}
const transaction: Transaction = {
uid: window.crypto.randomUUID(),
paymentMode: 'unknown',
};
getFieldName(transaction, 'uid'); // "uid"
getFieldName(transaction, 'paymentMode'); // "paymentMode"
getFieldName(transaction, 'asdf'); /*
~~~~~~
Argument of type '"asdf"' is not assignable to parameter of type 'keyof Transaction'.(2345) */
在 JavaScript(或 TypeScript)中,無法通過傳遞對屬性值的參考來派生字串屬性名稱。JavaScript 目前根本沒有這種元內省能力。
看來您的問題不僅與型別安全有關,還與 DX/人體工程學有關。上述解決方案確實需要提供屬性名稱,但在獲取 IntelliSense 提示之前要鍵入的額外字符數僅為 1(如果考慮空格,則為 2):
// For: obj.prop:
// desired:
fn(obj.p_)
// 012^
// proposed:
fn(obj, 'p_')
// 01234^
// The closing quote is auto-inserted by IntelliSense, just like the closing parenthesis.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/439046.html
標籤:javascript 打字稿 类型
