0

我在 Angular 12 版中使用 Zxing Scanner 组件。我在很多地方都遇到了这个错误。

/**
 * Returns a valid BarcodeFormat or fails.
 */
private getBarcodeFormat(format: string | BarcodeFormat): BarcodeFormat {
  return typeof format === 'string'
    ? BarcodeFormat[format.trim().toUpperCase()]
    : format;
}

错误在这一行[format.trim().toUpperCase()],当我悬停时它会显示Element implicitly has an 'any' type because index expression is not of type 'number'.ts(7015)

这是我截屏的错误代码...请查看

为什么会出现这个错误??我该如何解决?

我需要一个完美的解决方案,而无需更改angular.jsonpackage.json中的任何配置

4

1 回答 1

0

发生错误的原因是因为format它是一个字符串,可以是任何东西,所以当你在 中使用它时BarcodeFormat,打字稿不知道是否formatBarcodeFormat.

因此,我们需要告诉 typescriptformat实际上是BarcodeFormat.

为此,我们可以使用 的组合keyof typeof来获取键并在BarcodeFormat上进行类型转换format

private getBarcodeFormat(format: string | BarcodeFormat): BarcodeFormat {
    return typeof format === "string"
      ? BarcodeFormat[format.trim().toUpperCase() as keyof typeof BarcodeFormat]
      : format;
}

这是用于演示的代码框。

于 2021-06-11T13:17:49.920 回答