Omar Huseynov Omar Huseynov - 3 months ago 10
TypeScript Question

How to properly overload functions in typescript interfaces

I have following interface

interface foo1 {
add(num1: number, num2: number): number;
subtract(num1: number, num2: number): number;
}


Now I create an object in shape of foo1

let myFoo1: foo1;

myFoo1.add(5, 6); // OK
myFoo1.subtract(5, 6); // OK


Fine, now I create a new interface which I want it to act as an extension to the first one

interface foo2 {
add(num1: number, num2: number, num3: number): number;
}


Now I create a new object in shape of foo2

let myFoo2: foo2;

myFoo2.add(5, 6, 7); // OK
myFoo2.subtract(5, 6); // ERROR


Basing myFoo2 on foo2 interface makes me to use an "upgraded" version of add but now I can't access subtract function

Here's what I've come up with

let myFoo2: foo1 & foo2;

myFoo2.add(5, 6, 7); // OK
myFoo2.subtract(5, 6); // OK


Now I can use both the newer version of add and also access subtract function

Is it the proper way of doing stuff or am I doing something wrong?

Answer

You could extend foo1 by making the third argument optional, which it is - because you can pass two or three arguments to a method named add. This makes it compatible with the add method that is inherited.

interface foo1 {
    add(num1: number, num2: number): number;
    subtract(num1: number, num2: number): number;
}

interface foo2 extends foo1 {
    add(num1: number, num2: number, num3?: number): number;
}

You can then access all the members of foo1 and foo2.

var x: foo2;

x.add(1, 2);
x.add(1, 2, 3);
x.subtract(3, 1);

Alternatively, you can cut up the interfaces in a different way so that only the add method you want to make available appears:

interface foo {
    subtract(num1: number, num2: number): number;
}

interface foo1 extends foo {
    add(num1: number, num2: number): number;
}

interface foo2 extends foo {
    add(num1: number, num2: number, num3: number): number;
}

Now both foo1 and foo2 have the same subtract method, but different add methods.

var x: foo2;

// x.add(1, 2); not allowed now
x.add(1, 2, 3);
x.subtract(3, 1);