typescript - 如何为具有可选属性的类型赋值?
问题描述
这是我的类型:
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] 类型'{ id: number; 上不存在属性'制造商';名称:字符串;}'。
[ts] 类型 '{ id: number; 上不存在属性 'model' 名称:字符串;}'
我的代码有什么问题?
解决方案
只需添加类型信息:
let s: Supply = {
id: supply['supply_id'],
name: supply['name'],
}
否则 TS 将根据初始声明假定您的变量s
具有自己的类型{id: number, name: string}
推荐阅读
- revit-api - 如何使用 C# 在 revit 中获取计划元素数据
- java - 即使该位置有图像,也找不到文件异常
- xml - SED 多行搜索和替换错误
- github-api - Github API : Github App 在创建问题时应该获得什么权限
- r - 如何生成 2 个具有不同均值的不相关随机正态变量(使用 R)
- webpack-4 - 在 AngularJS1.5.11 中使用 Webpack4 时构建失败
- excel - 如何通过匹配值对Excel中的多列进行排序
- selenium-webdriver - 我试图从硒中调用铬。浏览器正在打开,但没有加载数据
- java - 有时定位服务无法在后台运行
- php - 如何在 WordPress 主题中创建电子商务 html 模板?