根据可选参数推断返回类型函数

时间:2020-04-28 11:28:43

标签: typescript

    // 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()来推断返回类型, 保持参数顺序。

1 个答案:

答案 0 :(得分:1)

使用overloads可以轻松地使返回类型取决于参数类型:

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值,则需要第三次重载:

function f(a: number, b?: number[], c?: number): string | false;

declare const possiblyUndefinedArray: number[] | undefined;
const boolOrStringTypeValue: string | false = f(9, possiblyUndefinedArray, 0);