【问题标题】:'ITestData' is assignable to the constraint of type 'IEntityData', but 'IEntityData' could be instantiated with a different subtype of constraint“ITestData”可分配给“IEntityData”类型的约束,但“IEntityData”可以用不同的约束子类型实例化
【发布时间】:2021-02-13 10:24:38
【问题描述】:

我有两节课。一个抽象超类:

export abstract class Entity<IEntityData> {
  protected readonly _source: IEntityData; // TODO: replace with private


  protected constructor(entityData: IEntityData) { this._source = entityData }

  get source(): IEntityData { return this._source }
}

和继承的类:

import { Entity } from './entity/entity';



interface ITestData {
  foo: string;
  bar: number;
}

export class Test<IEntityData extends ITestData = ITestData>
  extends Entity<IEntityData> {
  constructor(testData: ITestData) {
    super(testData);
  }

  get foo(): string { return this.source.foo }
  get bar(): number { return this.source.bar }
}

在构建过程中出现错误。我不明白我做错了什么。

src/app/data/models/test.ts:13:11 - error TS2345: Argument of type 'ITestData' is not assignable to parameter of type 'IEntityData'.
      'ITestData' is assignable to the constraint of type 'IEntityData', but 'IEntityData' could be instantiated with a different subtype of constraint 'ITestData'.
    
    13     super(testData);

【问题讨论】:

    标签: typescript generics inheritance constraints extend


    【解决方案1】:

    天哪!解决!我刚刚替换了这个:

    constructor(testData: ITestData) {
      super(testData);
    }
    

    用这个:

    constructor(testData: IEntityData) {
      super(testData);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-12-13
      • 2021-10-14
      • 2021-12-10
      • 1970-01-01
      • 2020-11-25
      • 2021-05-22
      • 2022-01-20
      • 2023-01-11
      • 2021-06-19
      相关资源
      最近更新 更多