在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 { .... }

最佳答案

它包含在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

07-25 20:41