Destructuring nullable objects

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);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)