【问题标题】:TypeScript Generic Classes: Cannot assign to Generic Type VariableTypeScript 泛型类:无法分配给泛型类型变量
【发布时间】:2016-12-08 17:11:09
【问题描述】:

我正在尝试为我的类使用通用接口。 我的类有一个泛型类型,它扩展了一个接口和一个具有该类型的类变量。但是,一旦我尝试为该变量赋值,编译器就会给我一个错误。(示例:A 类)

当我不扩展通用类型时,它可以工作。 (例:B类)

//Generic Classes problem
interface MyStateInterface {
    test?: number
}

class A<IState extends MyStateInterface> {
    protected state: IState;

    constructor() {
        // Error here
        this.state = {
            test: 1
        };
    }
}

class B<IState extends MyStateInterface> {
    protected state: MyStateInterface;

    constructor() {
        this.state = {
            test: 1
        };
    }
}

有没有人能解决这个问题?

【问题讨论】:

    标签: generics typescript compiler-errors


    【解决方案1】:
    class A<IState extends MyStateInterface> {
        protected state: IState;
    
        constructor() {
            this.state = { ...
    

    你所说的是IState 扩展 MyStateInterface。这意味着有人可以用比MyStateInterface 更具体的类型 来实例化A。具体来说,有人可以添加新的必需属性:

    interface MyCoolState extends MyStateInterface {
      required: string;
    }
    let x = new A<MyCoolState>();
    

    发生这种情况时,您的构造函数代码会通过使用缺少 required 的值初始化 state 来破坏 MyCoolState 的约定。

    如何解决此问题取决于您要执行的操作。通常当人们发现自己处于这种情况时,正确的做法是根本不使用泛型——子类已经用派生更多的类型覆盖 state 是合法的,所以如果这是您尝试启用的行为,您根本不需要泛型。

    【讨论】:

      猜你喜欢
      • 2018-09-19
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 2019-05-30
      • 2018-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多