例如,我有一個這樣的界面:
interface Account {
email: string;
enabled: boolean;
}
我想創建一個為這些欄位回傳默認值的方法。所以我有這樣的事情:
function defaultValue(propName:string) {
if (propName === 'email') return '';
if (propName === 'enabled') return true;
}
它運行良好,但是如果任何屬性發生Account更改,defautValue()即使它現在已損壞,該方法仍然可以編譯。
所以我想知道是否可以指定propName應該具有類似的型別property name of Account?或者在這種情況下我可以使用任何其他好的模式來強??制執行型別檢查?
uj5u.com熱心網友回復:
您可以使用函式在 if 陳述句的末尾斷言變數永遠不會出現并keyof T獲取鍵的聯合:
function assertNever(v: never): never {
throw new Error("Should never happen!");
}
function defaultValue(propName:keyof Account) {
if (propName === 'email') return '';
if (propName === 'enabled') return true;
assertNever(propName);
}
游樂場鏈接
您還可以通過使函式泛型來改善呼叫者體驗,但這將意味著實作中的一些型別斷言。
function defaultValue<K extends keyof Account>(propName:K): Account[K] {
if (propName === 'email') return '' as Account[K];
if (propName === 'enabled') return true as Account[K];
assertNever(propName);
}
let email = defaultValue('email') // string
let enabled = defaultValue('enabled') // boolean
游樂場鏈接
uj5u.com熱心網友回復:
您可以通過向引數添加更具體的字串型別來做到這一點propName。然后,使用 switch 陳述句進行智能型別推斷,即您正確地回傳了與函式中每個可能分支的回傳型別匹配的值。
interface Account {
email: string;
enabled: boolean;
shouldError: boolean;
}
function defaultValue(propName: keyof Account): Account[keyof Account] { // shows error for not always returning value
switch (propName) {
case "email":
return "";
case "enabled":
return true;
// uncomment this code to fix the error
// case "shouldError":
// return true;
}
}
TypeScript Playground 鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/419277.html
標籤:
上一篇:有沒有辦法從jestspyOnmockImplementation中訪問這個(當前實體)?
下一篇:Symfony\Component\Config\Definition\Exception\InvalidTypeException:路徑“doctrine.dbal”的型別無效。預期“陣列
