class A {
method : this = () => this;
}
我想要的是this,用作返回类型,代表当前类,即A的子类a。因此,方法仅返回与该类相同类型的值(不仅仅是基类 A)。
<小时/>我想我有类似的东西:
class A {
method : <T extends A> () => T = () => this;
}
但这似乎是多余的。我复制了A
。当然有更好的方法来做到这一点吗?..
最佳答案
你差不多明白了,method
属性的类型应该声明为 () => this
,而不仅仅是 this
。编译器知道当用作类型时,this
是 polymorphic
class A {
method : () => this = () => this;
}
class B extends A {
}
const b = new B();
const bb = b.method(); // inferred as const bb: B;
关于javascript - 如何在 typescript 中获取 "this"类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54975370/