0
我有一個函數有一些重載。TypeScript重載和可選參數
function foo(x: number, y: void): void;
function foo(x: number, y: number | string): number;
function foo(x: number, y: any) {
if (typeof y === "undefined") {
return;
}
return typeof y === "string"
? x/parseFloat(y)
: x/y;
}
除了使用可選的參數爲y
的,我專門用void
指定返回值。預期用例包括用undefined
作爲第二個參數調用的用例。
在另一個函數,我將它稱爲像這樣:
function bar(x: number, y?: number | string) {
const f = foo(x, y);
// Some other stuff
}
這將導致以下類型的錯誤:
Argument of type 'string | number | undefined' is not assignable to parameter of type 'string | number'.
Type 'undefined' is not assignable to type 'string | number'.
我的理解是foo
將採取的第二個參數中string | number | void
,並且當bar
調用它時,它將通過string
,number
或void
,TypeScript將清楚foo
' s的回報值。
達到預期效果的正確方法是什麼?