I'm attempting to grasp the concept of inferring generics in Typescript, but I can't seem to figure out where I'm going wrong. Although my concrete example is too large to include here, I've provided a link to a small TypeScript playground that demonstrates the issue I'm encountering.
Here's the link
In essence, I'm trying to infer a generic parameter from a class hierarchy:
type payloadType = {
[key:string]: string
}
type specificPayloadB = {
a: string
}
type specificPayloadC = {
a: string,
b: string
}
class A<TPayload extends payloadType = any> {}
class B<TPayload extends specificPayloadB = specificPayloadB> extends A<TPayload> {}
class C extends B<specificPayloadC> {}
type InferKeys<TType> = TType extends A<infer Keys> ? Keys : never;
class extender<
TType extends A,
TKeys = InferKeys<TType>
> {}
function getClass<TClass extends A>(): extender<TClass> {
return new extender<TClass>();
}
let testExtenderB = getClass<B>();
let testExtenderC = getClass<C>();
In the above example, there are no compilation errors. However, upon inspecting the returned variable types with Typescript, testExtenderB
is labeled as
extender<B<specificPayloadB>, payloadType>
, which is technically correct. But based on the context provided, it should be more accurately identified as extender<B<specificPayloadB>, specificPayloadB>
.
The same applies to the testExtenderC
variable, which is recognized as extender<C, payloadType>
instead of being acknowledged as
extender<C, specificPayloadC>
.
Is there a mistake in my approach? Can the correct identification of variables be achieved without explicitly specifying the types to Typescript?