Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript interface with multiple call signatures

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.

like image 652
Nisim Joseph Avatar asked Apr 17 '17 18:04

Nisim Joseph


Video Answer


1 Answers

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.

like image 130
Nisim Joseph Avatar answered Sep 28 '22 16:09

Nisim Joseph