实现说明
混入机制由一个类型别名加两个工厂函数组成。Constructor<T = object> 描述可构造的基类;Timestamped 和 Tagged 都接收 TBase extends Constructor 参数,返回叠加了新成员的 class extends Base——Timestamped 贡献 createdAt 与 stamp(),Tagged 贡献 tags 与 addTag()。
BuildLog 本身是只有 title 字段的普通类。组合行把两个混入叠加到它上面:Tagged(Timestamped(BuildLog))——Timestamped 先包住 BuildLog,Tagged 再包住这个结果——TaggedTimestampedLog 就是组合出来的构造器。实例同时带有全部层级的成员:log 以 new TaggedTimestampedLog('weekly deploy') 创建并立刻链上 .addTag('release').addTag('infra'),随后文件读取 log.title、调用 log.stamp()、拼接 log.tags——全程都有完整静态类型,没有 any 断言。InstanceType<typeof TaggedTimestampedLog> 把 typed 定型为同一个交集,typed.tags.push('audit') 因此通过类型检查。
使用要点
- 不需要依赖清单;标准库就是全部。
常见问题
这个示例需要哪些包?
一个都不用。代码用到的符号都在标准库里解析。 文件在加载时定义 Timestamped、Tagged。
核心语句
type Constructor<T = object> = new (...args: any[]) => T;
return `created at ${this.createdAt.toISOString()}`;
return class extends Base {
tags: string[] = [];
addTag(tag: string): this {
this.tags.push(tag);
return this;
}
};
代码示例
// Mixin(混入)的基础:用构造器签名约束基类
type Constructor<T = object> = new (...args: any[]) => T;
function Timestamped<TBase extends Constructor>(Base: TBase) {
return class extends Base {
createdAt = new Date('2026-11-14T09:30:00Z');
stamp(): string {
return `created at ${this.createdAt.toISOString()}`;
}
};
}
function Tagged<TBase extends Constructor>(Base: TBase) {
return class extends Base {
tags: string[] = [];
addTag(tag: string): this {
this.tags.push(tag);
return this;
}
};
}
class BuildLog {
title: string;
constructor(title: string) {
this.title = title;
}
}
const TaggedTimestampedLog = Tagged(Timestamped(BuildLog));
const log = new TaggedTimestampedLog('weekly deploy').addTag('release').addTag('infra');
console.log(log.title);
console.log(log.stamp());
console.log(log.tags.join(', '));
const typed: InstanceType<typeof TaggedTimestampedLog> = log;
typed.tags.push('audit');
console.log(typed.tags.length);