Artem Svirskyi
Artem Svirskyi

Reputation: 7839

Reuse function overloading in typescript

How to reuse function overloading in typescript?

For example, I have some function that is overloaded

function apply(value: number): number;
function apply(value: string): string;

function apply(value: any): any {
    return value;
}

And some other function that uses the apply function

function apply2(value: number | string) {
    return apply(value); // getting 'No overloads matching this call' here
}

const result = apply2(1);

Do I need to overload apply2, too?

Upvotes: 2

Views: 283

Answers (1)

Max
Max

Reputation: 788

The reason is that type number | string is neither assignable to type number, nor to string. This way the compiler does not know which overload you're using in apply2, and thus it cannot tell you what the return type of apply2 will be.

So, yes, the only way to solve this is by overloading the apply2 function

Upvotes: 1

Related Questions