如何在打字稿中输入 "this"

How to get "this" type in typescript

class A {
    method : this = () => this;
}

我要的是this,用作return类型,表示当前class,即subclass A的a。所以,方法只有returns与class相同类型的值(不是only基数class,A) .


我想我有类似的东西:

class A {
    method : <T extends A> () => T = () => this;
}

但这似乎是多余的。我复制了 A。当然有更好的方法来做到这一点?..

你差不多明白了,method 属性 的类型应该声明为 () => this,而不仅仅是 this。编译器理解当用作类型时,thispolymorphic

class A {
    method : () => this = () => this;
}

class B extends A {

}

const b = new B();

const bb = b.method(); // inferred as const bb: B;