这个
constructWhenReady
方法不关心泛型参数的类型
PropType
用实例化。它应该明确说明:
class Parent<PropType> {
static isReadyForConstruction = new Promise(r => setTimeout(r, 1000));
static async constructWhenReady<T extends typeof Parent<unknown>>(this: T): Promise<InstanceType<T>> {
// ^^^^^^^^^
await this.isReadyForConstruction;
return new this() as InstanceType<T>;
}
get something(): PropType {
// ...
}
}
注意,你甚至可以摆脱
as InstanceType<T>
写作时选角
static async constructWhenReady<T extends Parent<unknown>>(this: {new(): T; isReadyForConstruction: Promise<unknown>}): Promise<T> {
await this.isReadyForConstruction;
return new this();
}