typescript 关于 Promise 里 then 的参数类型的一个疑问

下面的代码在 fetch 之后的 then 里,根据 ok 状态进行不同的处理。

fetch('')
  .then(response => {
    if (response.ok) {
      return response.text()
    } else {
      // 返回一个 reject,让下面的 catch 捕获
      return Promise.reject(new Error(response.status.toString()))
    }
  })

但是 response 这里报错了一长串,前面是这样的:

No overload matches this call.
  Overload 1 of 3, '(onfulfilled?: ((value: Response) => string | PromiseLike<string>) | undefined, onrejected?: ((reason: any) => string | PromiseLike<string>) | undefined): Promise<string>', gave the following error.
    类型“(response: Response) => Promise<string> | Promise<void>”的参数不能赋给类型“(value: Response) => string | PromiseLike<string>”的参数。
      不能将类型“Promise<string> | Promise<void>”分配给类型“string | PromiseLike<string>”。

看起来因为这个 then 里面有两个类型的返回值,不符合 onfulfilled 的返回值,所以报错了。

不能将类型“Promise<string> | Promise<void>”分配给类型“string | PromiseLike<string>”。

我试了把其中一个返回值断言成 Promise<any> 可以解决,但这样有点糊弄的意思。如何用正确的方式解决呢?求教。

阅读 16.3k
1 个回答

throw new Error
按照评论里的方法, 可以了,谢谢!

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题