0

是否可以在没有 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”。

如何删除这些警告?

4

2 回答 2

1

为 指定类型obj

let obj: null | {key1: sometype; key2: sometype; } = null;

请注意,由于obj可能具有 value null,因此您需要围绕该解构赋值的保护或默认值:

if (obj) {
    const { key1, key2 } = obj;
}

或者

const { key1, key2 } = obj ?? {key1: defaultForKey1, key2: defaultForKey2};

或者

const { key1 = defaultForKey1, key2 = defaultForKey2 } = obj ?? {};

最后两者之间的区别在于如果objis not nullbut key1or key2has value会发生什么undefined(如果类型允许)。

于 2021-04-29T09:02:59.877 回答
1

useEffect 在您的初始渲染后运行 - 因此在第一次渲染时 obj 将为空,因此 TS 抱怨是正确的。

您需要在解构之前检查 obj 是否为空。另外,给它一个类型,例如

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
}

于 2021-04-29T09:04:29.273 回答