类型不可分配给类型“T",但可以使用约束类型的不同子类型实例化“T" [英] Type is not assignable to type 'T', but 'T' could be instantiated with a different subtype of constraint Type
问题描述
我正在尝试实施活动例程&带有打字稿的存储库逻辑.但是在处理泛型类型时遇到了一些问题.
Hi I'm trying to implement active routine & repository logic with typescript. But having some problems dealing with generic types.
我有一个抽象的 BaseModel
,它具有返回自身和自身子类型的 create 方法.为此,我说它将返回 BaseModel
.在具有从 BaseModel
扩展的泛型类型的存储库中,我包装了我的模型方法并使用泛型类型作为返回值.但是当我这样做时,它给了我以下错误.
I have an abstract BaseModel
which has create method that returns itself and subtype of itself. To do so I said it will return BaseModel
. In repository which has a generic type extends from BaseModel
, I wrapped my model methods and used generic type as returned value. But when I do that it gives me below error.
'BaseModel' 不能分配给类型 'T'.BaseModel"可分配给T"类型的约束,但T"可以用约束BaseModel"的不同子类型实例化.
当我用谷歌搜索时,发现了一些答案,比如在嵌套结构中重新分配泛型或复制时可能会发生这种情况.但我既没有分配一些东西,也没有一遍又一遍地定义相同的泛型
When I googled it, found some answers like it may happen when re-assigning the generic or dublicating in nested structures. But neither I'm assigning something nor define same generic over and over
为什么我会收到这种类型的错误,我该如何解决?
Why I'm getting this type error and how do I solve it ?
这是部分代码.
BaseModel.ts
BaseModel.ts
export abstract class BaseModel {
protected constructor(private attributes: any[] = []) {
}
create(attributes: any[] = null): BaseModel {
return this;
}
// ...
}
BaseRepository.ts
BaseRepository.ts
export class Repository<T extends BaseModel> {
constructor(private model: T) {
}
create(attributes: any[]): T {
return this.model.create(attributes);
}
// ...
}
推荐答案
那是因为 BaseModel
的 create
返回了不可分配给的 BaseModel
派生类型(子类型).它应该返回 this
:
That's because create
of BaseModel
returns BaseModel
which is not assignable to derived type (subtype). It should return this
:
create(attributes: any[] = null): this { ...
更多关于多态这种类型这里.
More on polymorphic this types here.
这篇关于类型不可分配给类型“T",但可以使用约束类型的不同子类型实例化“T"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!