0

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).

This is the error code I screenshot it... Please view it

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

ArumugaRaja
  • 15
  • 1
  • 9

1 Answers1

1

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.

Mic Fung
  • 5,404
  • 2
  • 7
  • 17
  • Yes. It's work now.. Thank you so much for your valuable time on this explanation – ArumugaRaja Jun 11 '21 at 16:05
  • Please accept the answer if you find it useful =). Here is the link of how to accept answer https://stackoverflow.com/help/someone-answers – Mic Fung Jun 11 '21 at 16:06
  • Yes, Now accepted. Sorry... I tried to vote for the answer but I need at least 15 reputations to cast a vote. and I don't know about accept the answer. So I didn't. – ArumugaRaja Jun 11 '21 at 16:44
  • I know. is okay. haha. you will earn point as well so don't hesitate to accept the answer that solved your problem =] – Mic Fung Jun 11 '21 at 16:46