A mixin is a function from a class to a subclass; const Sprite = Movable(Timestamped(Point)) builds a chain at runtime. TypeScript gives this pattern dedicated rules (TS 2.2):
- A mixin constructor type has one construct signature with a single
...args: any[]rest parameter and an object return type:type Constructor<T = {}> = new (...args: any[]) => T. - A mixin class is a class that
extendsa value whose type is a type parameter constrained to such a type:function M<TBase extends Constructor>(Base: TBase) { return class extends Base {} }. - Its result is
typeof C & TBase. When resolvingnewon that intersection, the mixin'sany[]signature is dropped and its instance members are merged into the base's signatures. Sonew Sprite("a", 2)is still checked againstPoint's(x: number, y: number), and the base's statics remain.
Constrained mixins. Write TBase extends Constructor<{ x: number; y: number }> and the mixin body can use this.x; applying it to a class without those members fails at the call (TS2345).
Rules the checker enforces. A mixin class's own constructor must be constructor(...args: any[]) and pass them to super(...args), otherwise TS2545. The constraint must be any[], not unknown[] (also TS2545). If the constraint is an abstract new signature (TS 4.2), the mixin class must be declared abstract (TS2797).
Library output. With declaration on, the returned class is an anonymous class type in the .d.ts, so private, protected and #private members are rejected (TS4094). The fix is an explicit return type: TBase & Constructor<Disposable>, with the members described by an interface.
The handbook's alternative, interface merging plus a runtime applyMixins that copies prototype methods, is unchecked: the interface promises members the copy might not provide.