Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring of optional props in Typescript

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?

like image 454
Sergei Klinov Avatar asked Sep 06 '25 03:09

Sergei Klinov


1 Answers

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.

like image 117
Mirco Bellagamba Avatar answered Sep 07 '25 22:09

Mirco Bellagamba