打字稿:函数重载

时间:2016-07-20 12:09:49

标签: typescript

在TypeScript中实现/实现此类函数重载的最简单方法是什么?

function Foo(
    param1: number,
    param2: string,
    param3: string,
    param4: () => void,
    param5: (xyz: string) => void): void { .... }

function Foo(
    param6: number,
    param3: string,
    param4: () => void,
    param5: (xyz: string) => void): void { .... }

1 个答案:

答案 0 :(得分:3)

它涵盖在Overloads section of the Functions docs中,但在您的情况下,它可能是这样的:

function Foo(
    param1: number,
    param2: string,
    param3: string,
    param4: () => void,
    param5: (xyz: string) => void): void; 
function Foo(
    param6: number,
    param3: string,
    param4: () => void,
    param5: (xyz: string) => void): void;

function Foo(...args: any[]): void {
    if (args.length === 5) {
        // 1st signature
    } else if (args.length === 4) {
        // 2nd signature
    } else {
        // error: unknown signature
    }
}

code in playground