Sometimes, we want to extend two classes with TypeScript.
In this article, we’ll look at how to extend two classes with TypeScript.
How to extend two classes with TypeScript?
To extend two classes with TypeScript, we merge all the properties in each class’ prototype into the class that we want to inherit from the two classes.
For instance, we write
class CanEat {
public eat() {
alert("eat.");
}
}
class CanSleep {
sleep() {
alert("sleep.");
}
}
const applyMixins = (derivedCtor: any, baseCtors: any[]) => {
baseCtors.forEach((baseCtor) => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
if (name !== "constructor") {
derivedCtor.prototype[name] = baseCtor.prototype[name];
}
});
});
};
class Being implements CanEat, CanSleep {
eat: () => void;
sleep: () => void;
}
applyMixins(Being, [CanEat, CanSleep]);
to define the applyMixins function.
In it, we loop through each class in baseCtors with forEach.
In the forEach callback, we get the property names of each class’ prototype with Object.getOwnPropertyNames.
And then we loop through each property name string with forEach.
If its name isn’t 'constructor'.
Then we assign baseCtor.prototype[name] to derivedCtor.prototype[name].
Next, we create the Being class that implements the CanEat and CanSleep classes.
And we call applyMixins to incorporate the property properties from the CanEat and CanSleep classes into the Being class’ prototype.
Conclusion
To extend two classes with TypeScript, we merge all the properties in each class’ prototype into the class that we want to inherit from the two classes.