Updated April 6, 2023
Introduction to TypeScript Mixins
In TypeScript, mixins can be defined as a class used to inherit the extra classes attribute and properties of that class, including this mixin class, which implements a variety of functionalities that can help the class access other methods properties of the classes. In general, mixins are the classes that have a set of code to access the other class properties and methods, which means that mixins can be used as code reusable functionality based on composing behavior that avoids inheritance ambiguity which was not supported in lower versions than typescript 2.2. Hence, building up of classes from the components that can be reused to build such partial classes is called mixin class.
Working of Mixin in Typescript with Examples
There is no particular syntax for writing mixin class as it is an extra class written to overcome the single inheritance problem, which means there is no restriction for extending a single class one at a time. Using mixin class is used in building simple partial classes, and this mixin class returns a new class. Therefore, the syntax of the mixin class cannot be defined exactly as it is a class that can take a constructor to create a class that has the functionalities of the constructor by extending the previous class and then returns a new class.
Suppose if we have two classes X and Y where class X wants to get the functionality of class Y, and this can be done using extending class X extends class Y, but in Typescript, mixins are used to extend the class Y, and therefore this function Y takes class X, and therefore it returns the new class with added functionality, and here the function Y is a mixin. In general, the mixin is a function that takes a constructor of the class to extend its functionality within the new class that is created, and this new class is returned.
The exact working of mixin can be demonstrated as a process of mixing multiple classes to a single target class, and this is done by using the “implement” keyword in Typescript for the target mixin class, which also uses some generic helper functions which helps to copy the properties of each mixin to the target mixin. But we cannot use interfaces as it can only extend the members of the class but not their implementations. Therefore, TypeScript provides mixins that help to inherit or extend from more than one class, and these mixins create partial classes and combine multiple classes to form a single class that inherits all the functionalities and properties from these partial classes.
Example of TypeScript Mixins
Different example are given below:
Example #1
Code:
console.log(" Demonstration of mixin using extends in Typescript")
class Courses {
name = "";
x = 0;
y = 0;
constructor(name: string) {
this.name = name;
}
}
type Constructor = new (...args: any[]) => {};
function Scale<TBase extends Constructor>(Base: TBase) {
return class Scaling extends Base {
_scale = 1;
setScale(scale: number) {
this._scale = scale;
}
get scale(): number {
return this._scale;
}
};
}
const Institute = Scale(Courses);
const numcourse = new Institute("Educba");
numcourse.setScale(3);
console.log(numcourse.scale);
Output:
In the above program, we are first creating class “Courses” which we are trying to scale the number of courses in the institute but to extend this class property we are using mixin concept that is first take a constructor as to make mixin extend the class “Courses” with new functionalities and the constructor is defined using “constructor” keyword. Then to extend the class “Courses”, we need to use the keyword “extends”, which is done n the function Scale where we are extending the constructor of the class to create a new class and return that class. The output of the code can be seen in the screenshot, where we are inheriting the property setscale() by extending the constructor and creating a new class named “Institute”, which is extended by the “Course” class.
Now let us see another example where it will take multiple classes and how the mixin works.
Example #2
Code:
console.log(" Demonstration of mixin in Typescript ")
class Mathfunc{
calculate(): void {
console.log("The math formula is getting executed");
}
}
class Variables {
display(): void {
console.log("The variables given are calculated and display the result");
}
}
class Add implements Mathfunc, Variables {
a: number;
b: number;
constructor(a, b) {
this.a = a;
this.b = b;
}
res(): number {
return this.a + this.b;
}
display(): void {
}
calculate(): void {
}
}
function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
Object.defineProperty(derivedCtor.prototype, name,
Object.getOwnPropertyDescriptor(baseCtor.prototype, name));
});
});
}
applyMixins(Add, [Mathfunc, Variables]);
let p: Add = new Add(9, 7);
p.calculate();
p.display();
let r = p.res();
console.log("The Additin of two given numbers is as follows:");
console.log(r);
Output:
In the above program, we can see we have classes “mathfunc”, “variables”, and “Add” where t display we are just providing “implements” keyword to extend the class properties. We are providing empty implementations which mixin helper functions will later replace. Therefore this mixin created iterate through properties of the base classes and then copy all these properties from these single classes into one single target class, and this done in the function apply mixin in the above program. Therefore we are trying to calculate the sum of two numbers where we have created a constructor with two different variables, and the result is displayed using the res() function, which returns the sum.
Conclusion
This article concludes with a demonstration of mixin in typescript where we saw how mixin works with keyword “extends” and “implements”. In this article, we saw an example of demonstrating the mixin which supports single inheritance by using these keywords in the program. We should also note that it may take much time in compiling the above approaches.
Recommended Articles
We hope that this EDUCBA information on “TypeScript Mixins” was beneficial to you. You can view EDUCBA’s recommended articles for more information.