I am referring to "this-typing" referenced here, and here.
It is my understanding that using this
as a type refers to the current class, or whatever is left of the dot (thereby allowing inherited methods to refer to their own class instead of their parent's class).
So can someone explain why this doesn't work:
class Test {
children: Array<this>;
constructor() {
this.children = [new Test()];
}
}
(My goal is to do that with an inherited class, but it doesn't work with a base class. Since this
is of type Test
why can't children
be an array of Test
?
Let's define derived class:
As you've already pointed out -
this
as type refers to current class, sochildren
member ofTestDerived
is of typeTestDerived[]
. So we can do something like this:If typescript will allow us to populate this array (in constructor of super) with instances of
Test
, we will loose type safety (someMethod
is not defined inTest
).No, when using
this
as a type you are referring to the instance and not the class.It's called Polymorphic this types and is meant to be used like this:
(code in playground)
If
Builder2D.x()
andBuilder2D.y()
would have returnedBuilder2D
:Then this would fail:
With:
In your scenario this isn't the case, you don't want to return
this
.As far as I'm aware there's no type for the class of
this
, but you can do:(code in playground)
Edit
Seems like there's an issue for that: Polymorphic "this" for static members.