首页 > 解决方案 > 使用扩展语法应用更新时如何处理空/未定义属性?

问题描述

考虑这个示例方法


GetCustomerWithPoints(customerId: number): Customer {
  const customer = this.customerService.getCustomer(customerId);
  const points = this.pointService.getPointsForCustomer(customerId);

   return {...customer, [customer.rewards.points]: points };
}

customer.rewardswhere is nullor的情况如何处理undefined?如果对象为空,我不关心设置点rewards,我只想在rewards对象存在时设置它们。

使用上面的代码,我得到了错误Object is possibly 'undefined'.

标签: typescriptecmascript-6

解决方案


您可以先检查要定义的实际值。然后,只有在您知道这样做是安全的情况下才能访问它:

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} : {}) 
  };
}

推荐阅读