Reuse function overloading in typescript

Viewed 155

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?

  • type of result must be number
  • generics are not the option (an example is simplified)
1 Answers

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

Related