3

What would be the easiest way to achieve / implement such a function overload in 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 Answer 1

4

It's covered in Overloads section of the Functions docs, but in your case it can be like this:

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.