是否可以解构来自函数调用的对象而不会出现 Typescript 抱怨?
文件1
...
let obj = null // <-- object initialization
...
useEffect(() => {
obj = functionCall(...) // <-- function call that populates the object
}, [obj])
const { key1, key2 } = obj // <-- object destructuring
我从 Typescript 收到以下抱怨
如何删除这些警告?
指定
obj
的类型:
let obj: null | {key1: sometype; key2: sometype; } = null;
请注意,由于
obj
可能具有值 null
,因此您需要围绕解构赋值设置一个保护或默认值:
if (obj) {
const { key1, key2 } = obj;
}
或
const { key1, key2 } = obj ?? {key1: defaultForKey1, key2: defaultForKey2};
或
const { key1 = defaultForKey1, key2 = defaultForKey2 } = obj ?? {};
后两者之间的区别在于,如果
obj
不是 null
但 key1
或 key2
具有值 undefined
(如果类型允许的话),会发生什么。
useEffect 在初始渲染之后运行 - 因此第一个渲染 obj 将为 null,因此 TS 的抱怨是正确的。
解构之前需要检查 obj 是否不为 null。另外,给它一个类型,例如
type MyType = { key1: string; key2: number; }; // for example
let obj: MyType | null = null;
if (obj) {
const { key1, key2 } = obj; // OK
} else {
// In here, obj is null
}
非空断言运算符:
const { key1, key2 } = obj!;