class A {
method : this = () => this;
}
我想要的是 this ,用作返回类型,以表示当前类,即A的子类a。因此,方法仅返回与该类相同类型的值(不是仅基类,A)。
我想我也有类似的东西:
class A {
method : <T extends A> () => T = () => this;
}
但这似乎是多余的。我复制了A
。当然有更好的方法可以做到这一点吗?..
答案 0 :(得分:1)
您几乎明白了,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;