Inheritance is an aspect of OOPs languages, which provides the ability of a program to create a new class from an existing class. It is a mechanism which acquires the properties and behaviors of a class from another class. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived/child/subclass. In child class, we can override or modify the behaviors of its parent class.
Before ES6 (ES2015) , JavaScript uses functions and prototype-based inheritance, but TypeScript supports the class-based inheritance which comes from ES6 version. The TypeScript uses class inheritance through the extends keyword.
PS:TypeScript does not support multiple inheritance.
TypeScript supports only single inheritance and multilevel inheritance.
Types of Inheritance
We can classify the inheritance into the five types. These are:
- Single Inheritance
- Multilevel Inheritance
- Multiple Inheritance
- Hierarchical Inheritance
- Hybrid Inheritance
How can we do, if we face a “multiple inheritance” issue in typescript ?
Workaround 1 :
first tip: whenever we come across a multiple inheritance problem, let´s think “multiple level inheritance over multiple inheritance” to see if that’ll do the job:
Class B extends A, Class C extendes B, and so on ...
Workaround 2
There is a feature in TypeScript that allows you to use Mixins to create re-usable small objects. You can compose these into larger objects using multiple inheritance (multiple inheritance is not allowed for classes, but it is allowed for mixins – which are like interfaces with an associated implenentation).
Here is a quick Mixins demo… first, the flavours that you want to mix:
class CanEat {
public eat() {
alert('Munch Munch.');
}
}
class CanSleep {
sleep() {
alert('Zzzzzzz.');
}
}
Then the magic method for Mixin creation (you only need this once somewhere in your program…)
function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
if (name !== 'constructor') {
derivedCtor.prototype[name] = baseCtor.prototype[name];
}
});
});
}
And then you can create classes with multiple inheritance from mixin flavours:
class Being implements CanEat, CanSleep {
eat: () => void;
sleep: () => void;
}
applyMixins (Being, [CanEat, CanSleep]);
Note that there is no actual implementation in this class – just enough to make it pass the requirements of the “interfaces”. But when we use this class – it all works.
var being = new Being();
// Zzzzzzz...
being.sleep();