Reputation: 1622
I'm trying to get the type of T3
to be inferenced properly in the example below, but it is just being shown as unknown
. I can't understand how it can properly infer the base type T2
when calling Testing.testIt
, but not the type parameter for the class it extends (T3
). Here is the running example. I was trying to figure out if the infer
keyword would be useful here, but I can't see how that would fit into this.
export interface Type<T> extends Function {
new (...args: any[]): T;
}
class GenericClass<T> {
}
class ChildClass extends GenericClass<string> {
}
class Testing {
static testIt<T3, T2 extends GenericClass<T3>>(testClass: Type<T2>): T3 {
console.log('testIt called');
return '' as any;
}
static testIt2(val: string): void {
console.log(val);
}
}
const result = Testing.testIt(ChildClass);
Testing.testIt2(result);
Upvotes: 1
Views: 54
Reputation: 134841
You'll want to define a helper to extract the type:
type ExtractGenericClassType<T> = T extends GenericClass<infer TInner> ? TInner : never;
class Testing {
static testIt<T extends GenericClass<any>>(testClass: Type<T>): ExtractGenericClassType<T> {
...
}
}
Moreover, you need to ensure that your generic class actually uses the generic type parameter, otherwise this will not work.
Upvotes: 2