【问题标题】:Infer the right generic type from a derived class从派生类中推断出正确的泛型类型
【发布时间】:2023-02-03 20:41:31
【问题描述】:

我正在尝试推断泛型类属性的类型。

例子:

abstract class A<T> {
  attr: T;
}

class B extends A<number> {
  attr = 1;
}

type Custom = {
  value: string;
};
class C extends A<Custom> {
  value = "1";
}

const a: A<any> = new B();
const b: A<any> = new C();

const instances: A<any>[] = [a, b];

instances.forEach((instance) => {
  // Here I need to set attr with the right type
  const attr = instance.attr;
});

我怎样才能做到这一点 ? 问题可能出在指定 a 和 b 的类型时使用 any。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    是的,你的类型注释让事情变得更糟,因为你正在扩大类型,而不是缩小它。你不需要它们,TS 已经知道缩小的类型:

    abstract class A<T> {
      attr: T;
    }
    
    class B extends A<number> {
      attr = 1;
    }
    
    type Custom = {
      value: string;
    };
    class C extends A<Custom> {
      value = "1";
    }
    
    const a = new B();
    const b = new C();
    
    const instances = [a, b];
    
    instances.forEach((instance) => {
      const attr = instance.attr; // This is now inferred as `number | Custom`
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      • 1970-01-01
      • 1970-01-01
      • 2014-03-22
      • 2023-03-14
      • 2023-04-01
      • 2011-10-09
      相关资源
      最近更新 更多