所以我有這樣的功能
export function myFunc<T>(dict: Record<string, T>, key: string, fallback?: T): ??? {
const value = dict[key] as T | undefined;
return value ?? fallback;
}
如果我呼叫 myFunc 并且回退被傳遞,它會知道 undefined 不再是回傳型別的可能性。例如
const x = myFunc<boolean>({}, "hello") // should be typed as boolean | undefined
const y = myFunc<boolean>({}, "hello", false) // should be typed as boolean only but is typed as boolean | undefined
現在,回傳型別總是 T | 未定義,即使我通過后備。有沒有辦法根據可選引數的存在來處理這種條件回傳型別?
uj5u.com熱心網友回復:
這就是函式多載。所以我們可以定義我們的 2 種變體,一種是定義回退并輸入為 T 的,另一種是明確未定義回退的。定義時回傳 T,未定義時回傳 T | 不明確的。而且,一旦我們這樣做,您也應該能夠洗掉 as T 演員表。
export function myFunc<T>(dict: Record<string, T>, key: string, fallback: T):T;
export function myFunc<T>(dict: Record<string, T>, key: string, fallback?: undefined):T | undefined;
export function myFunc<T>(dict: Record<string, T>, key: string, fallback?: T): T | undefined {
const value = dict[key] as T | undefined;
return value ?? fallback;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/390793.html
