简体   繁体   English

在 TypeScript 中,如何在具有多个类型参数的方法中获取泛型类型参数?

[英]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.

相关问题 TypeScript 泛型类型参数是通过函数推断出来的,而不是类型? - TypeScript generic type parameters are inferred with functions, but not type? 如何创建一个泛型 typescript 类型 function 并从参数类型推断出返回类型? - How do I make a generic typescript type function that has the return type inferred from the argument type? 具有多个类型参数的泛型中的推断类型 - Inferred type in generic with multiple type parameters TypeScript:在函数中强制使用通用推断的类型参数 - TypeScript: Enforce generic inferred type parameter in function 为什么泛型类型参数 T 在返回类型中是“未知的”? 如何键入此 function 以便正确推断返回类型? - Why is the generic type parameter T “unknown” in the return type? How can I type this function so that the return type is correctly inferred? 如果使用 function 参数,则无法推断 Typescript 类型 - Typescript type can not be inferred if function parameter is used 如何在打字稿中获取泛型类型的参数 - How to get the parameters of a generic type in typescript 如何获取Typescript中通用参数的类型? - How do I get the type of a generic parameter in Typescript? TypeScript:通用 function 类型参数是从错误参数推断的 - TypeScript: generic function type argument is inferred from a wrong parameter 如何在 Typescript 中获取 class 的通用参数类型 - How to get Generic Parameter Type of class in Typescript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM