0

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?

2
  • If you want it to act as an extension, why doesn't it extend it? See typescriptlang.org/docs/handbook/… Commented Aug 31, 2016 at 7:00
  • Because it doesn't. Here's an error message it gives if you do so: Interface foo2 incorrectly extends interface foo1. Type (num1: number, num2: number, num3: number) => void is not assignable to type (num1: number, num2: number) => number Commented Aug 31, 2016 at 7:06

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Can you please comment on foo1 & foo2 ? Should I use your method instead of mine and if so, why?

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.