打字稿:当结果可能是 Response 或 void 类型时,如何在 promise 的结果上调用 json() 方法?

Typescript: how to call json() method on result of promise when result could be of type Response or void?

在我的 React Native 应用程序中,我进行了 API 调用,然后尝试将 json() 方法应用于结果,如下所示:

await fetch(...)
  .catch(e => {...})
  .then(res => res.json().then(...)

Typescript 在 json() 上发出警告说 Property 'json' does not exist on type 'void | Response'

我想知道的:

  1. 有什么办法可以避免这个警告吗?
  2. 如果我调换 catchthen 的顺序,错误就会消失。但我希望 catch 只捕获来自 fetch() 的错误,而不是来自 then 块中的代码的错误。有办法实现吗?

使用optional chaining:

await fetch(...)
  .catch(e => {...})
  .then(res => res?.json?.().then(...)

The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

If I swap the order of catch and then, the error goes away. But I want catch to catch only errors from fetch(), not from the code in the then block. Is there a way to achieve this?

是,使用 .then(…, …) instead of .then(…).catch(…):

await fetch(...).then(res =>
  res.json().then(…)
, e => {
  …
});