[英]In TypeScript, how can i get a generic type parameter to be inferred in a method that has multiple type parameters?
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
.我试图在下面的示例中正确推断
T3
的类型,但它只是显示为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
).我无法理解在调用
Testing.testIt
时它如何正确推断基本类型T2
,但不是它扩展的 class 的类型参数( 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.我试图弄清楚
infer
关键字在这里是否有用,但我看不出它如何适合这个。
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);
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.此外,您需要确保您的泛型 class 实际使用泛型类型参数,否则这将不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.