![](/img/trans.png)
[英]How to infer return type based on return type of function in parameters
[英]Infer the return type function based on optional parameters
// Silly function that does nothing
function f(a: number, b?: number[], c?: number): string | boolean {
if (b === undefined)
return false;
b.push(a);
if (c) b.push(c);
return b.toString();
}
const boolTypeValue = f(5); // type: boolean | string
const boolTypeValue = f(5, undefined, 8); // type: boolean | string
const stringValue = f(9, [], 0); // type: boolean | string
是否可以定義 f() 以根據第二個可選參數值推斷返回類型,保持參數的順序。
使用重載可以輕松地使返回類型取決於參數類型:
function f(a: number, b?: undefined, c?: number): false;
function f(a: number, b: number[], c?: number): string;
function f(a: number, b?: number[], c?: number): string | false {
if (b === undefined)
return false;
b.push(a);
if (c) b.push(c);
return b.toString();
}
const boolTypeValue: boolean = f(5);
const boolTypeValue2: boolean = f(5, undefined, 8);
const stringTypeValue: string = f(9, [], 0);
如果您還希望能夠傳遞一個number[] | undefined
number[] | undefined
的值,您需要第三個重載:
function f(a: number, b?: number[], c?: number): string | false;
declare const possiblyUndefinedArray: number[] | undefined;
const boolOrStringTypeValue: string | false = f(9, possiblyUndefinedArray, 0);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.