I created a class called Foo
with a static property named instances
that holds references to all instances. Then, I have another class called Bar
which extends Foo
:
class Foo {
static instances: Foo[];
fooProp = "foo";
constructor() {
let ctor = this.constructor as typeof Foo;
ctor.instances.push(this);
}
}
class Bar extends Foo {
barProp = "bar";
}
The issue arises because the type of Bar.instances
is Foo[]
instead of Bar[]
, resulting in the following error:
let foo = new Foo();
let bar = new Bar();
Foo.instances[0].fooProp; // works
Bar.instances[0].barProp; // Property 'barProp' does not exist on type 'Foo'. ts(2339)
I attempted using InstanceType<this>
for the type of instances
, but encountered an error:
class Foo {
static instances: InstanceType<this>[]; // A 'this' type is available only in a non-static member of a class or interface. ts(2526)
...
}
This seems to be related to an issue discussed in the TypeScript repo about polymorphic behavior. Is it currently impossible to achieve what I want to do, or am I missing something?
Check out the playground link here.