Typescript Mixin example
ಮಿಥುನ್
Posted on July 5, 2020
Typescript doesn't allow multiple inheritance through classes, although an interface extends multiple classes but it doesn't inherit methods implementation, it inherits only method declaration.
class One {
one() {
}
}
class Two {
two() {
}
}
interface Three extends One, Two {
// inherits One's, Two's method declarations
one();
two();
}
There is another way to inherit methods from multiple special class(In typescript mixin used as function) called Mixin. According to Wikipedia, In object-oriented programming languages, a mixin (or mix-in) is a class that contains methods for use by other classes without having to be the parent class of those other classes. How those other classes gain access to the mixin's methods depends on the language.
Mixins are sometimes described as being "included" rather than "inherited". Basically in typescript Mixin is used to create a class. To this newly created class it adds new property and adds property from existing class.
it can be said as
Base/our class properties -> [ Mixin adds properties] -> NewClass
and then you can add few more properties
NewClass properties -> [ AnotherMixin adds properties] -> AnotherNewClass
Steps to use Mixin
- Create your class with properties, lets say User.
- Create constructor function
- Create Mixin function which return new class with new properties added by mixin and properties from User class.
Implementation
-
let's create a User class with property name
class User { name: string; }
-
let's create constructor function, used to create mixin class. refer this link for more details : instantiating generic type
// declaring generic type type Constructor<T = {}> = new (...args: any[]) => T;
-
A mixin function that adds new property and returns new class
function Timestamped<TBase extends Constructor>(Base: TBase) { // User is considered as Base and Base is extended by new class // return a class, combining "name" and "timestamp" return class extends Base { timestamp = Date.now(); // goes inside new class constructor }; }
New class is named as TimestampedUser
it consists of new property timestamp and "name" from User
const TimestampedUser = Timestamped(User);
const timestampedUserExample = new TimestampedUser();
timestampedUserExample.name = "vishruth";
console.log(timestampedUserExample.name); //"vishruth"
console.log(timestampedUserExample.timestamp);//1593976747100
You can create another Mixin and keep add properties to new class TimestampedNewMixinUser. like
// define NewMixin function here and call like below
const TimestampedNewMixinUser = Timestamped(NewMixin(User));
Posted on July 5, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.