12

I saw in TypeScript 2.2 the option for "overloading" function by defined Interface call signatures and I spent quite a time to understand how to use it.

so after working on it and "cracking" it I thought it will be worth to post it here.

the issue I started with was, for example:

interface Func1 {
    (num1: number, num2: number): number;
    (str1: number, str2: string): string;
}

function F1(num1: number, num2: number): number {
    return num1 + num2;
}

const f1: Func1 = F1;
console.log(f1(1, 2));

but the compiler did not pass it because the Func1 can't accept the F1 function.

I want to make overloading and I don't know what to do.

see answer below.

1 Answer 1

13

after digging it I found we can do quite of overloading. Overloading in TypeScript is not different from any other JavaScript code. it must be implemented in one function and not in multiple ones, like in C++. you need to make your function accept all options.

for example:

interface Func1 {
    (v1: number, v2: number): number;
    (v1: string, v2: string): string;
}

const f1: Func1 = (v1, v2): any => {
    return v1 + v2;
};
console.log(f1("1", "2"));
console.log(f1(1, 2));

the function f1 suppose to have types for all options of overloading interface call signature, if you set strong type it will block you because of the types are not castable. like in this example number not castable to string.

you also can create multiple functions which use of the interface call signature overloading and pass those to your f1 and if the type match it will pass. just make sure your function can handle all the interface call signature.

it important to check types in implemented function when using classes or if the function parameters are not simple, like above example, using typeof and control all options.

hope it helped.

Sign up to request clarification or add additional context in comments.

4 Comments

typeof is only meaningful on "simple" types though. Do not check with instanceof you are writing a bad API if you do. I can and will call your API using something that is not an instanceof your class and you will not be able to prevent it.
What if I want to make overloading with different generic arguments? e.g. interface GenericIdentityFn { <T>(arg: T): T; <T, F>(arg1: T, arg2: F): [T, F]; }
@FindOutIslamNow Multiple interface with the same name merge by default, so do their generics (also by name). interface I<A>, interface I<A,B>, interface I<C> == interface I<A,B,C>.
"Operator '+' cannot be applied to types 'string | number' and 'string | number'."

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.