这是我的类型:
export type Supply = {
id: number;
name: string;
manufacturer?: string;
model?: string;
}
这是我尝试分配给具有该类型的对象的方法:
return response['data']['supplies'].map((supply: ServerResponse.Supply) => {
let s = {
id: supply['supply_id'],
name: supply['name'],
}
if ('manufacturer' in supply) {
s.manufacturer = supply['manufacturer']
}
if ('model' in supply) {
s.model = supply['model']
}
return s;
});
我收到TypeScript警告:
[ts]属性'manufacturer'在类型'{id:number;上不存在。 名称:字符串; }'。
[ts]属性'model'在类型'{id上不存在 数;名称:字符串; }'
我的代码有什么问题?
答案 0 :(得分:2)
只需添加类型信息:
let s: Supply = {
id: supply['supply_id'],
name: supply['name'],
}
else TS将基于初始声明假定变量s
具有自己的类型{id: number, name: string}