[英]TypeScript: Type of the current class as a type variable
我想在 TypeScript 中聲明一個函數,該函數返回當前實例類型的類型,例如在返回this
的流暢 API 中。
“這種類型”是否有類型變量? (我寧願不使用丑陋的 Java 方式X<T extends X<T>>
。)
在 TypeScript 中還沒有辦法做到這一點。 有關投票/討論,請參閱問題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)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.