如何解决隐式有一个 `any` 类型因为索引表达式不是类型 'number'.ts(7015)
我在 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.json 或 package.json
中的任何配置解决方法
发生错误的原因是因为 format
是一个字符串并且可以是任何东西,所以当你在 BarcodeFormat
中使用它时,typescript 不知道 format
是否是其中之一BarcodeFormat
的键。
因此,我们需要告诉 typescript format
实际上是 BarcodeFormat
中键的一部分。
为此,我们可以使用 keyof typeof
的组合来获取 BarcodeFormat
中的键并在 format
上进行类型转换。
private getBarcodeFormat(format: string | BarcodeFormat): BarcodeFormat {
return typeof format === "string"
? BarcodeFormat[format.trim().toUpperCase() as keyof typeof BarcodeFormat]
: format;
}
这是用于演示的 codesandbox。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。