[英]How to specify types for overloaded function with multiple return types?
以下 TypeScript 代碼將無法編譯:
interface ZeroFunc {
(value: string): string;
(value: number): number;
}
const zero: ZeroFunc = (value: string | number) =>
typeof value === 'string' ? '' : 0;
錯誤:
Type '(value: string | number) => "" | 0' is not assignable to type 'ZeroFunc'.
Type 'string | number' is not assignable to type 'string'.
Type 'number' is not assignable to type 'string'. ts(2322)
它似乎在抱怨返回類型。
即使正確實現了該功能,該錯誤也是有道理的。
有沒有辦法正確指定這個函數的類型,而不使用any
作為返回類型?
是否有可能正確實現ZeroFunc
接口?
ZeroFunc 接口有兩個方法,它們與最終賦值的右側不匹配(一個接受字符串或數字並返回字符串或數字的函數)。
我想我會這樣做:
interface ZeroFunc {
(value: string | number): string | number;
}
const zero: ZeroFunc = (value: string | number) => typeof value === 'string' ? '' : 0;
但后來我想知道為什么需要接口。 你想強制執行什么?
更新:
我試圖強制執行,如果參數是一個數字,那么返回類型將是數字。 對於字符串參數,返回類型是字符串。
我想知道是否可能如下:
type ZeroFunc<T> = (value: T) => T;
// OK
const zeroString: ZeroFunc<string> = (value: string) => '';
// OK
const zeroNumber: ZeroFunc<number> = (value: number) => 0;
// Bad case caught:
// Type '(value: number) => string' is not assignable to type 'ZeroFunc<number>'.
// Type 'string' is not assignable to type 'number'
const zeroBad: ZeroFunc<number> = (value: number) => '';
// But this is also bad and is NOT caught
const zero: ZeroFunc<string | number> = (value: string | number) => 0;
但似乎不是 - 最后一種情況編譯,因為返回值匹配類型string | number
string | number
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.