【发布时间】:2020-08-03 09:03:18
【问题描述】:
拥有此代码:
export interface IModel {
id: string;
}
export interface StatusResponse<
TModel extends IModel = IModel,
TResponse = any
> {
item: TModel;
response: TResponse;
}
export class Transport<TItem extends IModel = IModel> {
save(item: TItem): StatusResponse<TItem> {
const result: StatusResponse<TItem> = {
item: { // << error
id: ""
},
response: {
stat: "ok"
}
};
return result;
}
}
在save 函数中,我收到了这个错误:
Type '{ id: string; }' is not assignable to type 'TItem'.
'{ id: string; }' is assignable to the constraint of type 'TItem', but 'TItem' could be instantiated with a different subtype of constraint 'IModel'.
令我困惑的是,接口StatusResponse 具有与Transport 的类Transport 相同的约束和默认值TModel TItem 但是,在save 函数中,它们表示为不匹配。
如果我像这样编写save 方法,就没有问题。
save(item: TItem): StatusResponse {
const result: StatusResponse = {
item: {
id: ""
},
response: {
stat: "ok"
}
};
return result;
}
请注意,我从 StatusResponse 中删除了泛型类型,因此它采用了默认值。
我不确定这里发生了什么。
【问题讨论】:
标签: typescript generics typescript-generics