class Alpha {
static construct<T extends typeof Alpha>(this: T): InstanceType<T> {
const v = new Alpha();
return v as InstanceType<T>;
}
}
class Beta extends Alpha {}
const x = Alpha.construct(); // generates Alpha
const y = Beta.construct(); // yields Beta
I have now introduced generics to Alpha
and Beta
, resulting in this:
class Alpha<T = string> {
static construct<T extends typeof Alpha>(this: T): InstanceType<T> {
const v = new Alpha();
return v as InstanceType<T>;
}
}
class Beta<T = number> extends Alpha<T> {}
const x = Alpha.construct(); // generates Alpha<unknown>
const y = Beta.construct(); // yields Beta<unknown>
In this scenario, I anticipate receiving Alpha<string>
and Beta<number>
, but the default values for generics are not being applied while using InstanceType<T>
.
Is there a way to include a generic and use a common method like .construct()
above where both classes return instances with defaulted generics?
I also attempted T['prototype']
without success.
I was hoping to create a custom InstanceType
, but it seems unattainable. Below is TypeScript's default definition for InstanceType
, which may not access the generics.
type InstanceType<T extends new (...args: any) => any> = T extends new (...args: any) => infer R ? R : any