Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Function overloading

Tags:

typescript

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 { .... }
like image 298
0xDECAFBAD Avatar asked Feb 11 '26 13:02

0xDECAFBAD


1 Answers

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)

like image 111
Nitzan Tomer Avatar answered Feb 14 '26 03:02

Nitzan Tomer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!