typescript - 使用扩展语法应用更新时如何处理空/未定义属性?
问题描述
考虑这个示例方法
GetCustomerWithPoints(customerId: number): Customer {
const customer = this.customerService.getCustomer(customerId);
const points = this.pointService.getPointsForCustomer(customerId);
return {...customer, [customer.rewards.points]: points };
}
customer.rewards
where is null
or的情况如何处理undefined
?如果对象为空,我不关心设置点rewards
,我只想在rewards
对象存在时设置它们。
使用上面的代码,我得到了错误Object is possibly 'undefined'.
解决方案
您可以先检查要定义的实际值。然后,只有在您知道这样做是安全的情况下才能访问它:
GetCustomerWithPoints(customerId: number): Customer {
const customer = this.customerService.getCustomer(customerId);
const points = this.pointService.getPointsForCustomer(customerId);
if(!customer.rewards) {
// rewards is null or undefined, just return the customer
return customer
}
// rewards are defined, append them to the customer:
return {...customer, [customer.rewards.points]: points };
}
您还可以使用简写替代方案:
GetCustomerWithPoints(customerId: number): Customer {
const customer = this.customerService.getCustomer(customerId);
const points = this.pointService.getPointsForCustomer(customerId);
return {
...customer,
...(customer.rewards ? {[customer.rewards.points]: points} : {})
};
}
推荐阅读
- git - Git 远程拉取不进行
- android - 启动后使用广播接收器启动应用程序在android 10中不起作用
- html - 网页上除了 CSS Wave Animation 什么都看不到
- php - SQLSTATE [42S22]:找不到列:1054 未知列“名称”,即使它存在于我的数据库表中
- html - 跨越标签在一起而不将文本分成两行
- java - 以编程方式发送大量 SMS - 发送报告问题
- quarkus - 如何在 Quarkus 中输入命令?
- css - 切换到暗模式时角度材质更改按钮样式
- c++ - 涉及 QuantLib::Date、std::min 和 boost/placeholders.hpp 的“C2676 二进制 '<' 运算符”编译错误
- django - django.db.utils.ProgrammingError:关系“testingland_mapcafes”不存在