Search code examples
javascripttypescriptdestructuring

How to avoid destructuring undefined values in JavaScript?


I get response registryReportSettings from server:

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

If it is null I get an error:

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

How to fix it using TS?


Solution

  • The error means that you try to deconstruct a possible undefined (Because you use optional chaining)

    You can do

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

    So you will always deconstruct an object