Mixins in TypeScript
Compose 类 behavior 从多个源 using mixin 模式相反的 继承.
你将学到
- 什么 mixins 是 and 为什么它们解决多个-继承需要
- 如何 定义 and apply mixins in TypeScript
- 输入 mixin 函数使用 constructor 类型 signatures
- Constrained mixins using generics and extends
概念讲解
The Mixin Pattern
JavaScript classes only support single inheritance — a class can extend one parent. Mixins are an alternative composition mechanism: you define small, focused classes (mixins) and combine them into a target class. Each mixin adds specific behavior (e.g. Disposable, Serializable, EventEmitter) without a deep inheritance hierarchy. The mixin pattern uses a function that takes a base class and returns an extended class.
Defining and Applying Mixins
A mixin is a function: 函数 Disposable<T extends Constructor>(基础: T) { 返回 类 extends 基础 { dispose() {} } }. You apply mixins by chaining: 类 MyComponent extends Disposable(Serializable(基础)) {}. The Constructor type (类型 Constructor<T = {}> = 新 (...args: 任何[]) => T) is the standard constraint for mixin base classes. Each mixin adds its methods to the resulting class.
Typing Mixins
Typing mixins correctly is tricky because TypeScript needs to know the combined type. The standard approach uses the Constructor type and generics to preserve the base class's type while adding the mixin's methods. For applied mixins, use interface declarations with extends to merge the types, or use ThisType for more advanced scenarios. Well-typed mixins give you full autocomplete and type checking on the composed class.
示例代码
// Base constructor type for mixins.
type Constructor<T = {}> = new (...args: any[]) => T;
// Mixin: adds timestamp tracking.
function Timestamped<TBase extends Constructor>(Base: TBase) {
return class extends Base {
createdAt = new Date();
updatedAt = new Date();
touch(): void {
this.updatedAt = new Date();
}
};
}
// Mixin: adds serialization.
function Serializable<TBase extends Constructor>(Base: TBase) {
return class extends Base {
serialize(): string {
return JSON.stringify(this);
}
};
}
// Base class.
class Entity {
constructor(public id: number) {}
}
// Compose: Entity + Timestamped + Serializable.
class Record extends Timestamped(Serializable(Entity)) {}
const rec = new Record(1);
console.log(rec.id); // 1
console.log(rec.createdAt); // Date
rec.touch();
console.log(rec.serialize()); // JSON string
Mixins compose 类 behavior 不使用多个继承. 每个 mixin 是函数那个 extends 基础类. Constructor 类型 constrains 基础. 链 mixins 到组合 behaviors: Timestamped(Serializable(Entity)).
动手试一试
- Code Diff
Compare mixin-based composition 使用 traditional 继承.
- Code Minifier
Observe 如何 mixin 类编译到 JavaScript constructor 链.
常见错误
错误写法
创建 deep mixin 链那个是 困难到 调试 and 类型
正确做法
Keep mixin 链 shallow — two or three levels at 大多数. Deep 链 produce confusing 类型错误 and 是困难到 trace. Prefer composition (有-) over deep mixin 链 (是-).
错误写法
Forgetting 到 declare 合并接口 for applied mixins
正确做法
Applied mixins 可能需要接口 declaration 到合并类型 for 完整类型检查. Declare '接口记录 extends Timestamped<...>, Serializable<...> {}' 到获取完整输入.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。