Typescript编译器错误带有继承的泛型类型
由于Typescript编译器错误带有继承的泛型类型,typescript,compiler-errors,typescript-typings,Typescript,Compiler Errors,Typescript Typings,由于输出变量中的键入错误,以下代码无法编译: 类型“{item:ModelInterface;}”不可分配给类型 “响应界面”。属性“项”的类型不兼容。 类型“ModelInterface”不可分配给类型“T” 接口模型接口{ } 接口响应接口{ 项目:T; } 班级商店{ get():响应接口{ 让输出:响应接口={ 项:this.getModel() }; 返回输出; } getModel():ModelInterface{ 返回null; } } get方法明确定义了T将始终扩展Mode
输出
变量中的键入错误,以下代码无法编译:
类型“{item:ModelInterface;}”不可分配给类型
“响应界面”。属性“项”的类型不兼容。
类型“ModelInterface”不可分配给类型“T”
接口模型接口{
}
接口响应接口{
项目:T;
}
班级商店{
get():响应接口{
让输出:响应接口={
项:this.getModel()
};
返回输出;
}
getModel():ModelInterface{
返回null;
}
}
get
方法明确定义了T
将始终扩展ModelInterface
,为什么我不能将显式ModelInterface
对象设置到项中而不出错
我可以通过以下方式克服此错误:
let输出:响应接口={
项:this.getModel()作为T
};
但它看起来像一个bug,我遗漏了什么,或者typescript编译器在这种情况下失败了
我试过了,但也失败了
有什么想法吗?事实上,T
从ModelInterface
扩展而来,这确保了任何T
实例都可以“转换”到ModelInterface
。但这并不意味着相反
例如:
class ModelInterface
{
public name: string;
}
interface ResponseInterface<T> {
item: T;
}
class ModelInterfaceExtended
{
public name: string;
public age: number;
}
class Store
{
get<T extends ModelInterface>(): ResponseInterface<T> {
let output: ResponseInterface<T> = {
item: this.getModel()
};
return output;
}
getModel(): ModelInterface {
return null;
}
}
const s = new Store();
let result = s.get<ModelInterfaceExtended>();
谢谢你的回答,这很有道理。然而,在我的实际案例中,事情并不像示例中那样简单。我的stores基类的定义与您在示例中所做的相同,但返回ModelInterface
的方法是在ModelInterface
接口本身上定义的(称为importValue
的方法返回ModelInterface
,因为它是唯一可以知道的类型)。但是我现在明白了为什么编译器会返回一个错误,我对此表示感谢。
class ModelInterface
{
public name: string;
}
interface ResponseInterface<T> {
item: T;
}
class ModelInterfaceExtended
{
public name: string;
public age: number;
}
class Store<T extends ModelInterface>
{
get(): ResponseInterface<T>
{
return {
item: this.getModel()
};
}
getModel(): T
{
return null;
}
}
const s = new Store();
let result = s.get();