简体   繁体   English

方法的泛型类型取决于 TypeScript 中 Class 的泛型类型

[英]Have a Generic Type of a Method Depend on the Generic Type Of the Class in TypeScript

I have a use case that can be expressed in pseudo-code as follows:我有一个可以用伪代码表示的用例,如下所示:

class Gen<T> {
  public doStuff<U>(input: U 
         /* If T is an instance of number, 
          then input type U should be an instance of custom type ABC, or
          If T is an instance of string,
          then input type U should an instance of custom type XYZ, else
          compile error */) {

     // do stuff with input
  }
}

Can this be expressed in TypeScript?这可以用 TypeScript 来表达吗?

Absolutely, with inference this is easily feasible.当然,通过推理,这很容易实现。 TypeScript allows you to "return" a different type based on a generic input type checking. TypeScript 允许您基于通用输入类型检查“返回”不同的类型。 You should just use a InferInputType<T> type like this:您应该只使用这样的InferInputType<T>类型:

type InferInputType<T> =
    T extends number ? ABC :
    T extends string ? XYZ :
    never;

then you can rewrite your Gen as:那么您可以将您的 Gen 重写为:

class Gen<T> {
    public doStuff(input: InferInputType<T>) {}
}

Then you can use your class like this:然后你可以像这样使用你的 class :

const genNumber = new Gen<number>();
genNumber.doStuff({ value: 10 });
genNumber.doStuff({ value: 'abc' }); // Error

You can see a working example in the playground: Playground Link您可以在操场上看到一个工作示例: Playground Link

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM