Is there a way to modify the constructWhenReady
method so that it returns only Child
, without any changes to the 'calling' code or the Child class? I am looking for a solution to implementing an async constructor, but existing solutions are not compatible when the Parent class is generic.
class Parent<PropType extends any> {
static isReadyForConstruction = new Promise(r => setTimeout(r, 1000));
static async constructWhenReady<T extends typeof Parent>(this: T): Promise<InstanceType<T>> {
await this.isReadyForConstruction;
return new this() as InstanceType<T>;
}
get something(): PropType {
// ...
}
}
class Child extends Parent<{ a: 'b' }> { }
// Error: '{ a: "b"; }' is assignable to the constraint of type
// 'PropType', but 'PropType' could be instantiated with a different
// subtype of constraint 'unknown'.
const x = await Child.constructWhenReady();
Reasoning: The goal is to ensure that less experienced developers writing Child
classes and using them have clean code (especially in test automation). One simple approach would be to require everyone to use await new Child().init()
, but it would be preferable to catch errors during coding rather than at runtime.