Home > Net >  Destructuring of optional props in Typescript
Destructuring of optional props in Typescript

Time:03-11

Suppose I have object with optional props of this kind of shape

interface MyObject {
  requiredProp: SomeType;
  optionalProp?: { 
    innerData: {
      innerProp1: string;
      innerProp2: number;
      innerProp3?: boolean;
    }
  }
}

const obj:MyObject = { ... }

But it seems that I can't easily destructure that optionalProp

const {innerProp1, innerProp2, innerProp3} = obj.optionalProp?.innerData;

because

Property 'innerProp1' does not exist on type '... | undefined'.

and same for the rest of destructured variables.

Is there an elegant and short way to do this keeping the type safety?

CodePudding user response:

You could use the empty object as a fallback.

const {innerProp1, innerProp2, innerProp3} = obj.optionalProp?.innerData ?? {};

But you should remember to check that each innerProp is not undefined before using it.

CodePudding user response:

Apart from the other correct answers, this can also be addressed in few other ways...

  1. By giving a value so that destructuring can be satisfied in case of undefined or null
const { innerProp1, innerProp2, innerProp3 } = obj.optionalProp?.innerData || {};
  1. By doing a null-ness check of optionalProp before destructuring.
if (obj.optionalProp) {
    const { innerProp1, innerProp2, innerProp3 } = obj.optionalProp?.innerData;
}

WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET

  • Related