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; });
我得到了类型脚本警告:
[ts]属性“manufacturer”在类型{id:number; 名称:string;}。 [ts]属性“model”在类型“{id: 数字名称:string;}'
[ts]属性“manufacturer”在类型{id:number; 名称:string;}。
[ts]属性“model”在类型“{id: 数字名称:string;}'
我的代码有什么问题?
只需添加类型信息:
let s: Supply = { id: supply['supply_id'], name: supply['name'], }
否则TS将假定您的变量 s 有自己的类型 {id: number, name: string}
s
{id: number, name: string}