[英]TypeScript generic type parameters are inferred with functions, but not type?
[英]In TypeScript, how can i get a generic type parameter to be inferred in a method that has multiple type parameters?
我试图在下面的示例中正确推断T3
的类型,但它只是显示为unknown
。 我无法理解在调用Testing.testIt
时它如何正确推断基本类型T2
,但不是它扩展的 class 的类型参数( T3
)。 这是 正在运行的示例。 我试图弄清楚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);
您需要定义一个帮助器来提取类型:
type ExtractGenericClassType<T> = T extends GenericClass<infer TInner> ? TInner : never;
class Testing {
static testIt<T extends GenericClass<any>>(testClass: Type<T>): ExtractGenericClassType<T> {
...
}
}
此外,您需要确保您的泛型 class 实际使用泛型类型参数,否则这将不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.