【问题标题】:Have a Generic Type of a Method Depend on the Generic Type Of the Class in TypeScript方法的泛型类型取决于 TypeScript 中类的泛型类型
【发布时间】:2020-04-26 15:27:43
【问题描述】:

我有一个用例可以用伪代码表示如下:

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 表达吗?

【问题讨论】:

    标签: typescript generics types


    【解决方案1】:

    当然,通过推理,这很容易实现。 TypeScript 允许您基于通用输入类型检查“返回”不同的类型。你应该像这样使用InferInputType&lt;T&gt; 类型:

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

    然后您可以将您的 Gen 重写为:

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

    然后你可以像这样使用你的类:

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

    您可以在操场上看到一个工作示例:Playground Link

    【讨论】:

    猜你喜欢
    • 2019-05-30
    • 2021-02-16
    • 2019-10-06
    • 2021-07-13
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    相关资源
    最近更新 更多