【问题标题】:Promise.all error - Type '(Video | undefined)[]' is not assignable to type 'Video[]'Promise.all 错误 - 类型 '(Video | undefined)[]' 不可分配给类型 'Video[]'
【发布时间】:2021-05-26 01:52:36
【问题描述】:

Promises.all 的类型有问题。它应该返回我的Video[] 接口,但我收到了类似的错误

类型“(Video | undefined)[]”不可分配给类型“Video[]”。 输入“视频 | undefined' 不能分配给类型 'Video'。 类型“未定义”不可分配给类型“视频”。

当我把它改成 (Video | undefined)[] 时,我的整个输入出现了错误,它应该又是 Video[]

我的代码在这里:

  const getDemo = async () => {
    setError({ show: false, msg: "" });
    try {
      setIsLoading(true);
      const resp: Video[] = await Promise.all(
        ourData.map(async (item) => {
          if (item.type === videoConstants.TYPE_YOUTUBE) {
            return getYouTubeVideo(item.id);
          }
          if (item.type === videoConstants.TYPE_VIMEO) {
            return getVimeoVideo(item.id);
          }
        })
      );
      setData([...data, ...resp]);
    } catch {
      setError({ show: true, msg: "failed to watch demo" });
    }
    setIsLoading(false);
  };

我正在使用我自己的函数来获取 API 以保持“DRY”规则 - 当我获取单个对象时可以,但是当我使用 Promise.all 从我们的数据库中获取所有集合时,我有一个我无法处理的错误。

【问题讨论】:

  • 您在地图中运行async 函数的任何原因? ourData.map(async (item)...
  • getYouTubeVideo 是否返回承诺?如果是这样,您需要在返回之前 await 以便您的 async 函数返回真实数据而不是承诺,或者您需要使地图函数不是异步的,因为它已经返回了承诺。 (异步函数只是返回 Promise 的常规函数​​,您无需编写所有 pomise 代码)。

标签: reactjs typescript promise


【解决方案1】:

以下代码:

if (item.type === videoConstants.TYPE_YOUTUBE) {
  return getYouTubeVideo(item.id);
}
if (item.type === videoConstants.TYPE_VIMEO) {
  return getVimeoVideo(item.id);
}

将返回类型为Video | undefined,因为没有else 块。

你可以试试这个(如果item.type只能取videoConstants中的两个值):

if (item.type === videoConstants.TYPE_YOUTUBE) {
  return getYouTubeVideo(item.id);
}
return getVimeoVideo(item.id);

或者也许:

if (item.type === videoConstants.TYPE_YOUTUBE) {
  return getYouTubeVideo(item.id);
}
if (item.type === videoConstants.TYPE_VIMEO) {
  return getVimeoVideo(item.id);
}
return {} as Video // TODO: depends on Video

或者如果你不能做到以上任何一个,这可能是你最后的选择 - const resp: (Video|undefined)[] = ...

【讨论】:

  • 如果他的item.type 总是videoConstants.TYPE_YOUTUBEvideoConstants.TYPE_VIMEO 怎么办?在这种情况下,不需要else。你是说他的代码会起作用吗?
  • 老兄,谢谢!真的行! :D 我在这个案子上花了几个小时。我是 Typescript 的新手,突然开始在我的公司使用 Typescript,你救了我的命。多谢一次! :)
  • @codemonkey 我不知道item.type 的所有可能值。但是,如果只有 两个 可能的值,那么 一个 if没有别的,但直接返回应该可以工作。
  • @๖JoJo 哈哈。乐于助人 :) 确保在 item.typevideoConstants.TYPE_VIMEO 时测试您的代码。
  • 我现在检查了一下,一切都很顺利 :D 我要了解更多 TypeScript 真的很喜欢这些所有界面和工作方式(真的很难创建一个有 bug 的应用程序)
猜你喜欢
  • 2018-09-29
  • 2023-01-18
  • 1970-01-01
  • 2022-10-22
  • 2022-10-14
  • 2020-07-22
  • 2021-08-16
  • 1970-01-01
  • 2016-06-24
相关资源
最近更新 更多