解构可为空的对象

类型脚本(或者我们应该说 ES)不允许解构 null/未定义的对象,它会抛出 TypeError。

假设我们有

let {a,b,c} = D;

其中 D可能是 null

如果我们需要使用 null 检查来进行条件解构赋值,那么我们就会创建一些样板代码来减少它。

在这种情况下使用它的最优雅的方法是什么,或者我们应该只对保证非空的对象使用解构?

37841 次浏览

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