如何保护代码免于解构 Javascript 中的空值?

hit*_*ker 0 javascript nullable destructuring

我是Javascript中解构和可选提议的忠实粉丝。

我不禁感到,在解构 null 或 undefined 值时,如果结果未定义,因为它在可选链中而不是抛出错误,那将非常有用。

例如:

const person = null
console.log(person?.age) // undefined
Run Code Online (Sandbox Code Playgroud)

然而:

const person = null
const { age } = person // runtime error
Run Code Online (Sandbox Code Playgroud)

它当然不会像这样工作,但是是否有一些 Babel 建议添加此功能?有什么解决方法吗?

Cer*_*nce 5

听起来您可能只想|| {}personis 为 null 的情况下使用来解构一个空对象(并且如果它也是 false 也恰好适用):

const person = null
const { age } = person || {};
console.log(age);
Run Code Online (Sandbox Code Playgroud)