Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 根据可选参数推断返回类型函数_Typescript - Fatal编程技术网

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

Typescript 根据可选参数推断返回类型函数,typescript,Typescript,是否可以定义f()以根据第二个可选参数值推断返回类型, 维护参数的顺序。用于根据参数类型轻松确定返回类型: // Silly function that does nothing function f(a: number, b?: number[], c?: number): string | boolean { if (b === undefined) return false; b.push(a);

是否可以定义f()以根据第二个可选参数值推断返回类型, 维护参数的顺序。

用于根据参数类型轻松确定返回类型:

    // 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
如果您还希望能够传递
number[]| undefined
值,则需要第三个重载:

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

您键入了
string[]
作为返回类型。您的意思是返回字符串数组吗?原因
b.toString()
正在对数组进行转换,而不是对数字进行转换。我刚刚更正了它
function f(a: number, b?: number[], c?: number): string | false;

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