Omar Huseynov - 1 year ago 45

TypeScript Question

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

`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

`interface foo2 {`

add(num1: number, num2: number, num3: number): number;

}

Now I create a new object in shape of

`let myFoo2: foo2;`

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

myFoo2.subtract(5, 6); // ERROR

Basing

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

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

Answer Source

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);
```