打字稿中的对象解构

问题描述 投票:0回答:3

是否可以解构来自函数调用的对象而不会出现 Typescript 抱怨?

文件1

  • 反应组件 1
...
let obj = null // <-- object initialization
...
useEffect(() => {
  obj = functionCall(...) // <-- function call that populates the object
}, [obj])
  • 反应组件2
const { key1, key2 } = obj // <-- object destructuring

我从 Typescript 收到以下抱怨

  • 类型“null”上不存在属性“key1”。
  • 类型“null”上不存在属性“key2”。

如何删除这些警告?

javascript reactjs typescript object object-destructuring
3个回答
2
投票

指定

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
(如果类型允许的话),会发生什么。


1
投票

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
}


0
投票

非空断言运算符:

const { key1, key2 } = obj!;
© www.soinside.com 2019 - 2024. All rights reserved.