Mixin in Typescript and how to implement it

In TypeScript, Mixin is a special class that allows the developer to combine multiple classes and their methods into one class. It provides an effective mechanism for code reuse and composition in object-oriented programming, enabling the incorporation of reusable behaviors without the limitations of traditional inheritance. With mixins, We can modularize code, reduce duplication, and create flexible class hierarchies, making it easier to build scalable and maintainable TypeScript applications.

Syntax

Let’s understand how we can implement mixins in TypeScript.

class BaseClass {
// Common functionality that can be used by multiple classes
}
// Mixin function
function Mixin<T extends Constructor>(Base: T) {
return class extends Base {
// Additional functionality added by the mixin
};
}
// Class that uses the mixin
class MyClass extends Mixin(BaseClass) {
// Class-specific functionality
}

In the BaseClass class, the functionalities are defined and can be used by multiple classes. After that, there will be a Mixin function that takes a constructor as a parameter and returns a new class that extends the BaseClass class. In the end, to apply Mixin to a class, we can simply extend the Mixin function with the base class, which in our case, would be BaseClass.

Code example

Click the “Run” button to execute the following code:

class BaseClass {
greet(): void {
console.log("Hi! from the base class");
}
}
// Mixin function
function Mixin<T extends new (...args: any[]) => any>(Base: T) {
return class extends Base {
additionalMethodgreet(): void {
console.log("Hi! from the additional method provided by the mixin");
}
};
}
// Class that uses the mixin
class MyClass extends Mixin(BaseClass) {
specificMethodgreet(): void {
console.log("Hi! from the Class that uses the mixin");
}
}
// Create an object of MyClass
const classObject = new MyClass();
// Call methods from BaseClass, Mixin, and MyClass
classObject.greet(); // Output: Hi! from the base class
classObject.additionalMethodgreet(); // Output: Hi! from the additional method provided by the mixin
classObject.specificMethodgreet(); // Output: Hi! from the Class that uses the mixin

Code explanation

  • Lines 1–5: We define a BaseClass class in which we define a greet the method that reflects a greeting message.

  • Lines 8–14: We define a Mixin function that takes a constructor as a parameter and returns a new class that extends the BaseClass class.

  • Lines 17–21: We define a MyClass which uses Mixin with a base class.

  • Line 24: We create an object of MyClass with the name of classObject.

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved