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.