为何ESLint未对函数调用返回的隐式any触发报错?
为什么ESLint未对代码中的隐式any触发报错?
你的代码中serializedResult的any类型来自browser.runtime.sendMessage返回的Promise<any>,当前配置下ESLint不会报错,原因如下:
1. @typescript-eslint/no-explicit-any规则的检测范围有限
你配置的@typescript-eslint/no-explicit-any仅针对代码中显式声明的any类型(比如let foo: any),不会检测从外部类型声明、第三方库返回的any类型。serializedResult的any是继承自声明文件中显式定义的Promise<any>,不属于该规则的检测范畴。
2. TypeScript的noImplicitAny规则不触发
tsconfig中的noImplicitAny是检测无明确类型声明且TypeScript无法自动推断类型的变量,但这里serializedResult的类型是明确从sendMessage的返回值推断而来(声明文件已显式标注为Promise<any>),属于显式传递的any,因此TypeScript编译器也不会抛出错误。
如何让ESLint检测此类场景
如果想要检测从外部any赋值的情况,需要启用类型检查类的ESLint规则:
- 将ESLint的
extends扩展为@typescript-eslint/recommended-type-checked或更严格的@typescript-eslint/strict-type-checked - 在
parserOptions中添加project: "./tsconfig.json",让ESLint能读取TypeScript配置进行类型校验
修改后的.eslintrc.json示例:
{ "env": { "browser": true, "es2021": true }, "extends": [ "eslint:recommended", "@typescript-eslint/strict-type-checked" ], "parser": "@typescript-eslint/parser", "parserOptions": { "ecmaVersion": "latest", "sourceType": "module", "project": "./tsconfig.json" }, "ignorePatterns": [ "bin/**" ], "plugins": [ "@typescript-eslint" ], "rules": { "prefer-rest-params": "off", "@typescript-eslint/no-explicit-any": "error" } }
启用后,@typescript-eslint/no-unsafe-assignment规则会对从any类型赋值的情况抛出错误,符合你的需求。
内容的提问来源于stack exchange,提问作者Sonny D
相关产品推荐
相关产品推荐

