Reputation: 2657
class A {
method : this = () => this;
}
What I want is for this, used as the return type, to represent the current class, i.e a subclass a of A. So, method only returns the values of the same type as the class (not only the base class, A).
I think I've got something similar with this:
class A {
method : <T extends A> () => T = () => this;
}
But this seems superfluous. I've duplicated A
. Surely there's a better way to do this?..
Upvotes: 0
Views: 1865
Reputation: 51769
You almost got it, the type of method
property should be declared as () => this
, not just this
. The compiler understands that when used as a type, this
is polymorphic
class A {
method : () => this = () => this;
}
class B extends A {
}
const b = new B();
const bb = b.method(); // inferred as const bb: B;
Upvotes: 1