til

How to write overloads for arrow functions

typescript

The third argument seems to be needed to correlate return/input types with the function body.

const greet: {
    (name: string): string
    (hellos: number): string
    (arg: string | number): string
} = (arg) => {
    if (typeof arg === "string") {
        return `Hello ${arg}!`;
    }
    return Array.from(Array(arg)).map(() => "Hello").join(' ');
}

greet("John");
greet(3);

// Outputs:
// Hello John!
// Hello Hello Hello

Check this TypeScript playground

I learnt this from @steveruizok