Safe destructuring using nullish coalescing or optional chaining

Ada*_*cha 4 javascript destructuring optional-chaining nullish-coalescing

Currently I am using below code for destructuring:

const myObj1 = {name: 'Abc'}
const {name} = myObj1
console.log(name)
const myObj2 = null
const {name2} = myObj2  // this will give error
Run Code Online (Sandbox Code Playgroud)

Now, since we have optional chaining, I can do this:

const myObj = {name: 'Abc'}
const {name} = myObj
console.log(name) // 'Abc'
const myObj2 = null
const name2 = myObj2?.myObj2
console.log(name2) // undefined
Run Code Online (Sandbox Code Playgroud)

是否有更好的方法或安全的方法来使用无效合并或可选链接进行解构?

You*_*saf 6

const name2 = myObj2?.myObj2 - 这不是解构。

myObj2?.myObj2将返回undefined您分配给的内容name2

你可以简单地做

const myObj2 = null;
const { name2 } = { ...myObj2 };
console.log(name2); // undefined
Run Code Online (Sandbox Code Playgroud)

如果你想使用空合并运算符,那么你应该使用它,如下所示:

const myObj2 = null
const {name2} =  myObj2 ?? {};
console.log(name2) // undefined
Run Code Online (Sandbox Code Playgroud)

如果myObj2为空或未定义,nullish 合并运算符将返回右侧的操作数,否则它将返回左侧的操作数,在您的情况下为myObj2.