Mixins
How Does A Mixin Work?
The pattern relies on using generics with class inheritance to extend a base class. TypeScript’s best mixin support is done via the class expression pattern. You can read more about how this pattern works in JavaScript here ↗.
To get started, we’ll need a class which will have the mixins applied on top of:
class Sprite {
name = "";
x = 0;
y = 0;
constructor(name: string) {
this.name = name;
}
}
Then you need a type and a factory function which returns a class expression extending the base class.
// To get started, we need a type which we'll use to extend
// other classes from. The main responsibility is to declare
// that the type being passed in is a class.
typeConstructor = new (...args: any[]) => {};
// This mixin adds a scale property, with getters and setters
// for changing it with an encapsulated private property:
functionScale<TBaseextendsConstructor>(Base: TBase) {
returnclassScalingextendsBase {
// Mixins may not declare private/protected properties
// however, you can use ES2020 private fields
_scale = 1;
setScale(scale: number) {
this._scale = scale;
}
getscale(): number {
returnthis._scale;
}
};
}
With these all set up, then you can create a class which represents the base class with mixins applied:
// Compose a new class from the Sprite class,
// with the Mixin Scale applier:
constEightBitSprite = Scale(Sprite);
constflappySprite = newEightBitSprite("Bird");
flappySprite.setScale(0.8);
console.log(flappySprite.scale);
Constrained Mixins
In the above form, the mixin’s have no underlying knowledge of the class which can make it hard to create the design you want.
To model this, we modify the original constructor type to accept a generic argument.
// This was our previous constructor:
typeConstructor = new (...args: any[]) => {};
// Now we use a generic version which can apply a constraint on
// the class which this mixin is applied to
typeGConstructor<T = {}> = new (...args: any[]) =>T;
This allows for creating classes which only work with constrained base classes:
type Positionable = GConstructor<{ setPos: (x: number, y: number) => void }>;
typeSpritable = GConstructor<Sprite>;
typeLoggable = GConstructor<{ print: () =>void }>;
Then you can create mixins which only work when you have a particular base to build on:
function Jumpable<TBase extends Positionable>(Base: TBase) {
returnclassJumpableextendsBase {
jump() {
// This mixin will only work if it is passed a base
// class which has setPos defined because of the
// Positionable constraint.
this.setPos(0, 20);
}
};
}
Alternative Pattern
Previous versions of this document recommended a way to write mixins where you created both the runtime and type hierarchies separately, then merged them at the end:
// Each mixin is a traditional ES class
classJumpable {
jump() {}
}
classDuckable {
duck() {}
}
// Including the base
classSprite {
x = 0;
y = 0;
}
// Then you create an interface which merges
// the expected mixins with the same name as your base
interfaceSpriteextendsJumpable, Duckable {}
// Apply the mixins into the base class via
// the JS at runtime
applyMixins(Sprite, [Jumpable, Duckable]);
letplayer = newSprite();
player.jump();
console.log(player.x, player.y);
// This can live anywhere in your codebase:
functionapplyMixins(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)
);
});
});
}
This pattern relies less on the compiler, and more on your codebase to ensure both runtime and type-system are correctly kept in sync.
Constraints
The mixin pattern is supported natively inside the TypeScript compiler by code flow analysis. There are a few cases where you can hit the edges of the native support.
Decorators and Mixins #4881
↗
You cannot use decorators to provide mixins via code flow analysis:
// A decorator function which replicates the mixin pattern:
constPausable = (target: typeofPlayer) => {
returnclassPausableextendstarget {
shouldFreeze = false;
};
};
@Pausable
classPlayer {
x = 0;
y = 0;
}
// The Player class does not have the decorator's type merged:
constplayer = newPlayer();
player.shouldFreeze;
// The runtime aspect could be manually replicated via
// type composition or interface merging.
typeFreezablePlayer = Player & { shouldFreeze: boolean };
constplayerTwo = (newPlayer() asunknown) asFreezablePlayer;
playerTwo.shouldFreeze;
Property 'shouldFreeze' does not exist on type 'Player'.
Static Property Mixins #17829
↗
More of a gotcha than a constraint. The class expression pattern creates singletons, so they can’t be mapped at the type system to support different variable types.
You can work around this by using functions to return your classes which differ based on a generic:
function base<T>() {
classBase {
staticprop: T;
}
returnBase;
}
functionderived<T>() {
classDerivedextendsbase<T>() {
staticanotherProp: T;
}
returnDerived;
}
classSpecextendsderived<string>() {}
Spec.prop; // string
Spec.anotherProp; // string