TypeScript:当前 class 的类型作为类型变量
TypeScript: Type of the current class as a type variable
我想在 TypeScript 中声明一个 returns 当前实例类型的函数,例如API returns this
.
是否有 "this type" 的类型变量? (我宁愿不使用 X<T extends X<T>>
的丑陋 Java 方式。)
在 TypeScript 中还没有办法做到这一点。请参阅 voting/discussion 的问题 https://github.com/Microsoft/TypeScript/issues/285。
现在可以实现流畅的界面:
class FluentInterface {
aMethod(): this {
return this;
}
}
我知道这不是您想要的,但对于我的用例来说, 已经足够好了:
export class Component{
init(config?: { [field in keyof this]?: this[field] }) {
Object.assign(this, config)
}
}
我想在 TypeScript 中声明一个 returns 当前实例类型的函数,例如API returns this
.
是否有 "this type" 的类型变量? (我宁愿不使用 X<T extends X<T>>
的丑陋 Java 方式。)
在 TypeScript 中还没有办法做到这一点。请参阅 voting/discussion 的问题 https://github.com/Microsoft/TypeScript/issues/285。
现在可以实现流畅的界面:
class FluentInterface {
aMethod(): this {
return this;
}
}
我知道这不是您想要的,但对于我的用例来说,
export class Component{
init(config?: { [field in keyof this]?: this[field] }) {
Object.assign(this, config)
}
}