本文介绍了方法的泛型类型取决于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
  }
}

这可以用TypeScript表示吗?

Can this be expressed in TypeScript?

推荐答案

当然,根据推断,这很容易实现.TypeScript允许您基于常规输入类型检查来返回"其他类型.您应该只使用 InferInputType< T> 类型,如下所示:

Absolutely, with inference this is easily feasible. TypeScript allows you to "return" a different type based on a generic input type checking. You should just use a InferInputType<T> type like this:

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

然后您可以将Gen重写为:

then you can rewrite your Gen as:

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

然后您可以像这样使用您的课程:

Then you can use your class like this:

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

这篇关于方法的泛型类型取决于TypeScript中类的泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 18:10