Mixins in TypeScript
A function taking a class and returning an extended one.
type Constructor<T = object> = new (...args: any[]) => T;
function Timestamped<TBase extends Constructor>(Base: TBase) {
return class extends Base {
created = new Date(0);
age(): number {
return Date.now() - this.created.getTime();
}
};
}
function Countable<TBase extends Constructor>(Base: TBase) {
return class extends Base {
count = 0;
increment(): number {
this.count += 1;
return this.count;
}
};
}
class Tour {
constructor(public slug: string) {}
}
const Tracked = Countable(Timestamped(Tour));
const tour = new Tracked("basics");
tour.increment();
console.log(tour.slug, tour.count, tour.age() > 0);
How it works
- The constructor type is what makes it composable.
- Mixins stack, each adding members.
- It is how TypeScript does multiple inheritance.
Keywords and builtins used here
DateTBaseanyclassconstconstructorextendsfunctionnumberpublicreturnstringthistype
The run, in numbers
- Lines
- 29
- Characters to type
- 610
- Tokens
- 173
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 104 seconds.
Step 4 of 4 in Classes, step 4 of 19 in Classes & patterns.