2

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 Answer 1

1

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

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.