Mixins in Typescript

Aayush Pagare
2 min readMay 12, 2024
Photo by Jessica Rockowitz on Unsplash

What is multiple inheritance ?

Multiple inheritance is a feature found in some programming languages that allows a class to inherit properties and behavior from more than one parent class. In other words, a subclass can have multiple Super classes.

That’s a common use case right ?

Lets say we are developing an application where there are two classes class Father and class Mother. The Child class must need to inherit some of the props from Father and some from Mother. In such cases we can use Multiple Inheritance.

Multiple Inheritance is not supported in Typescript?

 class Mother { 
name:string
constructor(name: string) {
this.name=name
}

hasBeautifullEyes( ) {
console.log("Has beautifull eyes")
}

isEmotional() {
console.log("Is Emotional")
}
}

class Father {
fatherName: string
constructor(name: string) {
this.fatherName = name
}

hasLogicalBrain( ) {
console.log('Has logical brain')
}

hasAngerIssues( ) {
console.log('Has anger issues')
}
}

//This is not allowed in Typescript
class Daughter extends Father, Mother {

}

Why Multiple Inheritance is not supported directly ?

In multiple inheritance, it’s possible for a subclass to inherit methods or attributes with the same name from multiple parent classes. This can lead to ambiguity and name clashes, where it’s unclear which method or attribute should be used. Resolving such conflicts requires careful management and can lead to code that is difficult to understand and maintain.

class Father {
giveAdvice() {
console.log("Father's advice: Work hard and be honest.");
}
}

class Mother {
giveAdvice() {
console.log("Mother's advice: Always be kind and compassionate.");
}
}

class Child extends Father, Mother {
// Code for class Child
}

const child = new Child();
child.giveAdvice(); // <-- Which advice should be taken ???

Mixins — Alternative to Multiple inheritance

class Mother { 
name:string
constructor(name: string) {
this.name=name
}

hasBeautifullEyes( ) {
console.log("Has beautifull eyes")
}

isEmotional() {
console.log("Is Emotional")
}
}

class Father {
fatherName: string
constructor(name: string) {
this.fatherName = name
}

hasLogicalBrain( ) {
console.log('Has logical brain')
}

hasAngerIssues( ) {
console.log('Has anger issues')
}
}
//from ts official doc
function applyMixins(derivedCtor: any, constructors: any[]) {
constructors.forEach((baseCtor) => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
Object.defineProperty(
derivedCtor.prototype,
name,
Object.getOwnPropertyDescriptor(baseCtor.prototype, name) || Object.create(null)
);
});
});
}

interface Child extends Father, Mother {}
class Child implements Child {}

applyMixins(Child, [Father, Mother])
const c = new Child()
c.hasAngerIssues(),
c.hasBeautifullEyes()

--

--

Aayush Pagare

System design and coding enthusiast, tackling tech challenges with passion and dedication.