0

Suppose I have the following two interface

interface Bird {
    type: 'bird';
    flyingSpeed: number;
}
interface Horse {
    type: 'horse';
    runningSpeed: number;
}

Now I want to create another interface that will extend either the Bird or Horse interface. I know that it's possible by using type. I am just curious about whether it is possible by using an interface or not like the following

interface Animal extends Bird | Horse {
    name: string
}
sahed moral
  • 345
  • 3
  • 13
  • Possibly, this post refers to the same question: https://stackoverflow.com/questions/17865620/multiple-inheritance-workarounds – Juan Castillo Mar 12 '23 at 17:27
  • What should `Animal` behave like? `(Animal extends Bird) & (Animal extends Horse)` or `Animal extends (Bird & Horse)`? Something else? – kelsny Mar 12 '23 at 18:08
  • As asked, this is impossible. An interface can only be built on a single object type (or intersection of object types) with statically known members. A union is not such a type, so this is not possible. Does that fully address the question? If so I could write up an answer explaining; if not, what am I missing? – jcalz Mar 12 '23 at 20:06
  • @jcalz You know type support either A or B option. So I just wondering whether it's also possible in the case of interface or not? – sahed moral Mar 13 '23 at 04:59
  • 2
    Maybe there's a communication barrier here? My response to this comment would be nearly identical to my previous comment. Let me try again: No, it is impossible. What you are calling "A or B" is a **union**, and interfaces cannot extend unions. Does that make sense now? If so, I will write an answer post. – jcalz Mar 13 '23 at 14:08

1 Answers1

0

In this case, I would take the opposite way. I would first create an abstract interface of the Animal and then create individual subspecies from it. The AnimaSpecies type is not mandatory, you can skip it and define the type only in Bird and Horse.

type AnimaSpecies = 'bird' | 'horse';

interface Animal {
    name: string,
    type: AnimaSpecies;
}

interface Bird extends Animal {
    type: 'bird';
    flyingSpeed: number;
}

interface Horse extends Animal {
    type: 'horse';
    runningSpeed: number;
}