Optional nested destructuring

The Problem

I faced an issue while de-structuring an optional nested property.

// product.js
export const productA = { name: 'A', price: { value: 20 } };
export const productB = { name: 'B'  };

// index.js
import { productA, productB } from './product';
const { price: { value } } = productA;

/* the actual problem, it throws with the error
"cannot read property 'value' of undefined" */
const { price: { value } } = productB;

The Solution

Let me know, what do you guys think of it?

const { price?: { value } } = productB;

Thanks!

2 Likes

The current solution for optional properties are default initialisers:

const { price: { value } = {} } = productB;
1 Like

This is true. One thing I don't like about this is that TypeScript (maybe Flow and/or others too) will complain about this:

Property 'value' does not exist on type '{}'.ts(2339)

this can be worked around with any but that's not very desirable:

const { price: { value } = {} as any } = productB;

using something like ?: would be more concise and, in my opinion, easier to read a long chain of destructuring places the = {} far away, etc.

1 Like