0
下面的代码失败,因为在output
可变打字错误的编译:打字稿编译器错误一般类型具有继承
类型“{项:ModelInterface; }'不能分配给 'ResponseInterface'类型。财产'物品'的类型是不相容的。 类型'ModelInterface'不可分配给'T'类型。
interface ModelInterface {
}
interface ResponseInterface<T> {
item: T;
}
class Store {
get<T extends ModelInterface>(): ResponseInterface<T> {
let output: ResponseInterface<T> = {
item: this.getModel()
};
return output;
}
getModel(): ModelInterface {
return null;
}
}
的get
方法明确定义T
总是会延长ModelInterface
,我为什么不能设置一个明确的ModelInterface
对象为item
没有一个错误?
我可以通过做克服这个错误:
let output: ResponseInterface<T> = {
item: this.getModel() as T
};
但它看起来像一个bug,我失去了一些东西或打字稿编译器只是在这种情况下会失败呢?
我试过在typescript playground但它也失败了。
有什么想法?
谢谢您的回答,这非常有意义。然而,在我的真实情况下,事情并不像示例中那么简单。我的商店基类是按照你的例子定义的,但返回一个'ModelInterface'的方法是在'ModelInterface'接口本身定义的(称为'importValues'的方法返回一个'ModelInterface',因为它唯一可以知道的类型)。但我现在明白为什么编译器会返回一个错误,我为此感谢你。 – Stnaire