为什么打字稿认为我在放入承诺捕获块后我的财产可能无效?

Ste*_*ath 4 promise typescript

async function fetchMpdData(mpdUrl: string): Promise<MPDFileContainer> {
  const data = await fetch(mpdUrl)
    .then((response): Promise<string> => response.text())
    .catch(
      (error): void => {
        throw new FetchError(`Error fetching file ${mpdUrl}: ${error}`);
      },
    );
  return parseStringMpd(data);
}
Run Code Online (Sandbox Code Playgroud)

parseStringMpd需要一个字符串。将data传递到parseStringMpd与失败:

类型'string |的参数 无效”不能分配给“字符串”类型的参数。

在SO上还有其他一些问题,它们讨论了诺言如果未通过catch块将如何导致该data属性无效。但是在我的情况下,catch块引发了错误。因此,将永远无法获得所抱怨的数据。

打字稿解析器是否无法处理此问题?

Pal*_*leo 5

您的错误在这里:

  (error): void => {
    throw new FetchError(`Error fetching file ${mpdUrl}: ${error}`);
  },
Run Code Online (Sandbox Code Playgroud)

您声明返回类型是void(什么never都不返回的函数)而不是(永不返回的函数)。您可以将其更改为,: never但我建议您让TypeScript进行推断:

  error => {
    throw new FetchError(`Error fetching file ${mpdUrl}: ${error}`);
  },
Run Code Online (Sandbox Code Playgroud)

…但是,如果您使用async/ await,则可以使用它们重写代码:

async function fetchMpdData(mpdUrl: string): Promise<MPDFileContainer> {
    try {
        const response = await fetch(mpdUrl)
        const data = await response.text()
        return parseStringMpd(data);
    } catch (error) {
        throw new Error(`Error fetching file ${mpdUrl}: ${error}`)
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,变量responsedata通过推断正确键入。声明它们的类型是没有用的。