TypeScript中对内联数组使用forEach报错,求解决方法
TypeScript中forEach遍历数组报错的解决方案
问题场景
编写了如下TypeScript代码:
['components.d.ts', '.eslintrc.js'].forEach(fileName => { console.log(fileName) })
这段代码在JavaScript中完全有效,但TypeScript却抛出了以下错误:
Element implicitly has an 'any' type because expression of type '".eslintrc.js"' can't be used to index type 'void'. Property '.eslintrc.js' does not exist on type 'void' Unsafe call of an `any` typed value. eslint(@typescript-eslint/no-unsafe-call) Left side of comma operator is unused and has no side effects. ts(2695)
当前tsconfig配置如下:
{ "compilerOptions": { "target": "ESNext", "module": "ESNext", "moduleResolution": "node", "baseUrl": "./", "paths": { "@/*": [ "src/*" ], "@templates/*": [ "src/templates/*" ] }, "resolveJsonModule": true, "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "noImplicitAny": true, "strictNullChecks": true, "strictFunctionTypes": true, "strictBindCallApply": true, "strictPropertyInitialization": true, "noImplicitThis": true, "noFallthroughCasesInSwitch": true, "noImplicitOverride": true, "skipLibCheck": true }, "exclude": [ "./node_modules" ], "include": [ "src/**/*" ] }
错误原因分析
从报错信息里的Left side of comma operator is unused and has no side effects可以看出,核心问题是数组表达式没有被正确解析为独立语句。大概率是这段代码的前一行缺少分号,导致TypeScript将前一行的表达式和当前数组解析成了逗号运算符的组合。比如前一行是一个返回void的函数调用时,会被解析成:
// 错误示例:前一行无分号 someVoidFunction()['components.d.ts', '.eslintrc.js'].forEach(...)
此时TypeScript会认为你在尝试用数组元素去索引void类型的返回值,自然就会抛出类型错误。
解决方案
修复代码上下文的分号问题
在数组表达式前加上分号,或者确保前一行语句末尾有分号,让TS正确识别数组为独立语句:;['components.d.ts', '.eslintrc.js'].forEach(fileName => { console.log(fileName) })显式声明数组类型
如果是类型推断异常导致的问题,可以显式指定数组为字符串数组,强制TS识别类型:const fileNames: string[] = ['components.d.ts', '.eslintrc.js'] fileNames.forEach(fileName => { console.log(fileName) })验证strict配置影响(可选)
虽然你的strict: true配置是规范的,但如果以上方法无效,可以暂时关闭noImplicitAny选项测试是否是严格模式的推断限制,但不建议长期关闭,优先修复语法层面的问题。
内容的提问来源于stack exchange,提问作者JD Solanki
相关产品推荐
相关产品推荐

