Destructuring nullable objects

TypescriptObjectEcmascript 6

Typescript Problem Overview


Typescript (or should we say ES) doesn't allow destructuring of null/undefined objects. It throws TypeError.

So, lets say we have something like

let {a,b,c} = D;

where D could be null.

If we need to do conditional destructuring assignment with null-checks then we create boilerplate code for something that was meant to reduce it.

What is the most elegant way of using it in cases like that or should we use destructuring only for guaranteed non-null objects?

Typescript Solutions


Solution 1 - Typescript

You can use an empty object as fallback, and if D is null or undefined the assigned variables will be undefined.

const D = null;
const { a, b, c } = D || {};

console.log(a, b, c);

Using typescript you need to add the correct type (or any) to the FALLBACK object (TS playground). For example:

interface Obj {
    a?: string;
    b?: string;
    c?: string;
}

const D = null;
const { a, b, c } = D || {} as Obj;

console.log(a, b, c);

Another option is to use object spread, since spreading null or undefined results in an empty object (see this SO answer).

const D = null;
const { a, b, c } = { ...D };

console.log(a, b, c);

Using typescript you need to add the types to the variable that you spread, and the object that you destructure. For example (TS Playground):

interface Obj {
    a?: string;
    b?: string;
    c?: string;
}

const D = null;
const { a, b, c } = { ...D as any } as Obj;

console.log(a, b, c);

If you need to handle nested destructuring, use defaults:

const D = null;
const { a, a: { z } = {}, b, c } = { ...D };

console.log(a, b, c, z);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiondee zgView Question on Stackoverflow
Solution 1 - TypescriptOri DroriView Answer on Stackoverflow