Typescript (或者我们应该说ES)不允许解构null/未定义的对象。它抛出TypeError。
所以,假设我们有这样的东西
let {a,b,c} = D;其中D可以是null。
如果我们需要使用null-check进行条件解构赋值,那么我们会为一些旨在减少它的东西创建样板代码。
在这种情况下使用它最优雅的方式是什么,或者我们应该只对有保证的非空对象使用解构吗?
发布于 2017-07-20 17:15:24
您可以使用空对象作为备用对象,如果D为null或undefined,则分配的变量将为undefined。
const D = null;
const { a, b, c } = D || {};
console.log(a, b, c);
使用typescript,您需要向回退对象(TS playground)添加正确的类型(或any)。例如:
interface Obj {
a?: string;
b?: string;
c?: string;
}
const D = null;
const { a, b, c } = D || {} as Obj;
console.log(a, b, c);另一种选择是使用object spread,因为传播null或undefined会产生一个空对象(see this SO answer)。
const D = null;
const { a, b, c } = { ...D };
console.log(a, b, c);
使用typescript,您需要将类型添加到您传播的变量和您解析的对象中。例如(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);如果您需要处理嵌套解构,请使用默认值:
const D = null;
const { a, a: { z } = {}, b, c } = { ...D };
console.log(a, b, c, z);
https://stackoverflow.com/questions/45210111
复制相似问题