Mixins
| Compose with functions | |
| Apply to classes | |
| Name conflicts | |
| When mixins win |
Compose with functions
A mixin is a function that takes a base class and returns an extended class. Each mixin adds one capability, such as logging or timestamps, without editing the original.
Because mixins are plain functions, you combine them by nesting calls. The result reads as a recipe: start from a base, then layer each behavior in order.
type Ctor = new (...args: any[]) => {};
function Tagged<T extends Ctor>(Base: T) {
return class extends Base {
tag = "card";
};
}
Apply to classes
Applying means passing your class through the mixin call. The returned class has all old members plus the new field or method, fully typed for later use.
Keep the base tiny and let mixins supply cross cutting extras. Tests can then cover the base alone and each mixin alone with no tangled setup.
class Card {
title = "Draft";
}
const TaggedCard = Tagged(Card);
const one = new TaggedCard();
console.log(one.tag);
Name conflicts
Two mixins can add the same member name with different meaning. The last one applied wins silently, which is a classic source of confusing bugs.
Prevent this with distinct names, such as createdLabel versus updatedLabel. Explicit names cost a few letters and save long debugging sessions.
class Base {
label = "base";
}
class Child extends Base {
createdLabel = "made";
}
When mixins win
Mixins win when several unrelated classes need the same small behavior. One shared function beats copy pasted methods scattered across the codebase.
Prefer plain composition or a helper function when only one class needs the logic. Reach for a mixin when the second and third consumers appear.
function withStamp<T extends Ctor>(Base: T) {
return class extends Base {
stamped = true;
};
}
const StampedCard = withStamp(Tagged(Card));
Next: Branding nominal types
Article author: Arthur Isaev