如何配置ESLint使其对隐式推断的inferred any类型进行更严格校验?
ESLint检查隐式推断any的规则方案
TypeScript项目配置(仅TS项目支持类型级校验)
你需要先安装@typescript-eslint/eslint-plugin和@typescript-eslint/parser作为开发依赖,之后在ESLint配置中启用以下规则即可覆盖需求:
@typescript-eslint/no-implicit-any:全局扫描所有隐式推断为any的位置,符合你要的全量检查需求@typescript-eslint/no-implicit-any-catch:专门针对你举例的catch块error参数默认隐式any的场景做校验@typescript-eslint/no-unsafe-member-access:禁止访问any类型变量上的属性/方法,你示例中的error.message如果error是any类型会直接触发警告,无需手动 hover 检查变量类型
配置示例
// .eslintrc.js 核心配置片段 module.exports = { parser: '@typescript-eslint/parser', plugins: ['@typescript-eslint'], rules: { '@typescript-eslint/no-implicit-any': 'warn', '@typescript-eslint/no-implicit-any-catch': 'warn', '@typescript-eslint/no-unsafe-member-access': 'warn' } }
你也可以配合tsconfig.json中的noImplicitAny: true配置,在TS编译阶段就抛出隐式any相关错误,形成双层校验。
调整后的安全代码示例
开启规则后,你需要对catch块做类型收窄避免隐患:
try { // 执行业务逻辑 } catch (error: unknown) { if (error instanceof Error) { sendErrorToApi(error.message) } else { // 处理非Error类型的抛出值 sendErrorToApi(String(error)) } }
注意:纯JavaScript项目没有静态类型信息,ESLint原生无法识别隐式any,需要先接入TypeScript或者开启TypeScript的 checkJs 能力才能实现上述校验。
内容的提问来源于stack exchange,提问作者Fernando H'.'
相关产品推荐
相关产品推荐

