【发布时间】: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