You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 07:38:41