【问题标题】:Type is not assignable to type 'T', but 'T' could be instantiated with a different subtype of constraint Type类型不可分配给类型“T”,但可以使用不同的约束类型子类型来实例化“T”
【发布时间】:2020-11-25 08:03:38
【问题描述】:

您好,我正在尝试使用 typescript 实现活动例程和存储库逻辑。但是在处理泛型类型时遇到了一些问题。

我有一个抽象的BaseModel,它具有返回自身和自身子类型的创建方法。为此,我说它将返回BaseModel。在具有从BaseModel 扩展的泛型类型的存储库中,我包装了我的模型方法并使用泛型类型作为返回值。但是当我这样做时,它会给我以下错误。

'BaseModel' is not assignable to type 'T'.   'BaseModel' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'BaseModel'.

当我用谷歌搜索它时,发现一些答案可能会在重新分配通用或在嵌套结构中复制时发生。但我既没有分配东西,也没有一遍又一遍地定义相同的泛型

为什么我会收到这种类型的错误,我该如何解决?

这是部分代码。

BaseModel.ts

export abstract class BaseModel {
  protected constructor(private attributes: any[] = []) {
  }

  create(attributes: any[] = null): BaseModel {
    return this;
  }
  // ...
}

BaseRepository.ts

export class Repository<T extends BaseModel> {
  constructor(private model: T) {
  }

  create(attributes: any[]): T {
    return this.model.create(attributes);
  }
  // ...
}

【问题讨论】:

    标签: typescript typescript-typings typescript-generics


    【解决方案1】:

    这是因为BaseModel 中的create 返回的BaseModel 不能分配给派生类型(子类型)。它应该返回this:

    create(attributes: any[] = null): this { ...
    

    Playground

    更多关于这种类型的多态here

    【讨论】:

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