简体   繁体   中英

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

Is it possible to define f() to infer the return type based on the second optional parameter value, maintaining the order of the parameters.

Use overloads to easily have the return type depend on the parameter type:

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);

If you also want to be able to pass a number[] | undefined number[] | undefined value, you need a third overload for that:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM