简体   繁体   中英

Implicitly has an `any` type becoz index expression is not of type 'number'.ts(7015)

I am using Zxing Scanner component in Angular version 12. I faced this error in many places..

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

Error is in this line [format.trim().toUpperCase()] and when I hover it will show Element implicitly has an 'any' type because index expression is not of type 'number'.ts(7015) .

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

Why this error came?? How do I resolve it??

I need a perfect solution without change any configuration in my angular.json or package.json

The reason why the error occurred is because format is a string and can be anything so when you use it in BarcodeFormat , typescript doesn't know whether format is one of the keys of BarcodeFormat .

Therefore, we need to tell typescript format is actually part of the keys in BarcodeFormat .

To do it, we can use the combination of keyof typeof to get the keys in BarcodeFormat and do type casting on format .

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

Here is the codesandbox for demonstration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM