如何避免解构 JavaScript 中的未定义值?

How to avoid destructuring undefined values in JavaScript?

我从服务器收到响应 registryReportSettings

this.getRegistrySettings(registry.Id).subscribe((registryReportSettings: { extended: ReportPropertiesRequest }) => {
  const { objectProperties, reportProperties, textProperties } = registryReportSettings?.extended;
}

如果是null我得到一个错误:

TypeError: Cannot destructure property 'objectProperties' of '(intermediate value)(intermediate value)(intermediate value)' as it is undefined.

如何使用 TS 修复它?

错误的意思是你试图解构一个可能的undefined(因为你用的是optional chaining

你可以做到

const { objectProperties, reportProperties, textProperties } = registryReportSettings?.extended ?? {};

所以你总是会解构一个对象