-
Notifications
You must be signed in to change notification settings - Fork 0
traits.Function.implTraits
github-actions[bot] edited this page Jun 8, 2026
·
2 revisions
@zenstone/ts-utils / traits / implTraits
implTraits<
T,Traits>(ctor, ...traits):void
Defined in: src/traits/core.ts:96
将一个或多个 trait 对象的属性描述符复制到 ctor.prototype,实现运行时扩展。
所有 trait 类型通过 UnionToIntersection 合并为交叉类型后作为 ThisType
绑定,因此每个 trait 内部的 this 都能感知:
- 宿主类的属性和方法
- 同一 trait 内的其他方法
- 其他 trait 的方法(跨 trait 互调)
class MyClass {
name = 'test'
}
type GreetTrait = { greet(): string }
implTraits(MyClass, {
greet() {
return `hello, ${this.name}` // this.name ← MyClass ✓
},
})
interface MyClass extends GreetTrait {}type GreetTrait = { greet(): string }
type DisplayTrait = { display(): string }
implTraits(MyClass,
{
greet() {
return `hi, ${this.display()}` // this.display ← DisplayTrait ✓
},
},
{
display() {
return this.name // this.name ← MyClass ✓
},
},
)
interface MyClass extends GreetTrait, DisplayTrait {}工厂函数内部定义对象时,编译器无法自动感知宿主类型,需通过显式 this
参数或泛型约束来补充:
type PrefixTrait = { prefixed(): string }
function createPrefixTrait<Host extends { name: string }>(prefix: string) {
return {
prefixed(this: Host) {
return `${prefix}::${this.name}` // this.name ← Host 约束 ✓
},
}
}
implTraits(MyClass, createPrefixTrait<MyClass>('app'))
interface MyClass extends PrefixTrait {}- 跳过
constructor属性,避免破坏原型链 - 使用
defineProperty而非赋值,能正确处理 getter / setter - 类型侧需配合
interface MyClass extends TraitA, TraitB {}声明合并 - 使用 Biome 时需加两处 biome-ignore:class 声明前 suppress
noUnsafeDeclarationMerging, interface 声明前 suppressnoUnusedVariables:// biome-ignore lint/suspicious/noUnsafeDeclarationMerging: implTraits guarantees runtime implementation class MyClass { ... } implTraits(MyClass, { ... }) // biome-ignore lint/correctness/noUnusedVariables: trait type extension via implTraits interface MyClass extends MyTrait {}
T extends object
Traits extends object[]
Constructor<T>
目标类构造器
...{ [K in string | number | symbol]: Traits[K] & ThisType<T & UnionToIntersection<Traits[number]>> }
一个或多个 trait 实现对象
void