Angular12使用Zxing Scanner出现TS7015报错如何不修改配置解决
报错产生原因
- 你当前使用的
BarcodeFormat是Zxing库定义的数字枚举类型,TypeScript 对数字枚举默认的索引签名仅支持数字类型(用于反向映射),不支持直接传入任意字符串作为索引键。 - 代码中
format.trim().toUpperCase()的返回值是宽泛的string类型,TS无法确认该字符串一定是BarcodeFormat枚举的合法键名,因此触发ts(7015)类型错误,提示索引表达式类型不合法、值隐式为any。
解决方法(无需修改任何配置文件)
通过类型断言+合法性校验的方式在代码层面解决,既满足TS类型校验要求,也能避免运行时传入非法格式的异常:
修改后的代码如下:
/** * Returns a valid BarcodeFormat or fails. */ private getBarcodeFormat(format: string | BarcodeFormat): BarcodeFormat { if (typeof format === 'string') { const formatKey = format.trim().toUpperCase() as keyof typeof BarcodeFormat; // 可选校验:避免传入非法格式返回undefined if (BarcodeFormat[formatKey] === undefined) { throw new Error(`无效的条码格式: ${format}`); } return BarcodeFormat[formatKey]; } return format; }
- 核心逻辑:用
as keyof typeof BarcodeFormat把格式化后的字符串断言为BarcodeFormat枚举的合法键类型,告诉TS该值一定是枚举的已有键,消除类型报错。 - 若能确保上游传入的字符串一定是合法格式,也可以简化代码直接返回:
private getBarcodeFormat(format: string | BarcodeFormat): BarcodeFormat { return typeof format === 'string' ? BarcodeFormat[format.trim().toUpperCase() as keyof typeof BarcodeFormat] : format; }
内容的提问来源于stack exchange,提问作者ArumugaRaja
相关产品推荐
相关产品推荐

