Junior — Middle
Can multiple inheritance be used in TypeScript?
sobes.tech AI
Answer from AI
In TypeScript, multiple inheritance of classes is not directly supported, meaning a class cannot inherit from multiple classes simultaneously. This is because JavaScript (on which TypeScript is based) only supports single inheritance.
However, in TypeScript, you can implement a semblance of multiple inheritance using mixins — functions that add functionality to a class.
Example of a mixin:
class CanEat {
eat() {
console.log('Eating');
}
}
class CanWalk {
walk() {
console.log('Walking');
}
}
class Person {}
interface Person extends CanEat, CanWalk {}
applyMixins(Person, [CanEat, CanWalk]);
function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
derivedCtor.prototype[name] = baseCtor.prototype[name];
});
});
}
const p = new Person();
p.eat(); // Eating
p.walk(); // Walking
Thus, multiple inheritance is achieved through composition and mixins, not through direct inheritance of multiple classes.