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

ESLint报no-undef错误:DocumentEventMap未识别的解决方法及咨询

问题:ESLint提示DocumentEventMap未定义的解决方法及是否为@typescript-eslint bug

我定义了如下TypeScript类型:

export type ClickEventProps = {
  handler: (event: MouseEvent) => void;
  additionalEvents?: Array<keyof DocumentEventMap>;
};

ESLint抛出no-undef错误,提示DocumentEventMap未定义。想找到无需禁用该行规则的修复方法,同时询问这是否属于@typescript-eslint的bug?

相关依赖版本

"@typescript-eslint/eslint-plugin": "^5.59.7",
"@typescript-eslint/parser": "^5.59.7",

.eslintrc.js配置

module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 'latest',
    sourceType: 'module',
  },
  plugins: ['prettier', 'react', '@typescript-eslint'],
};

tsconfig.json配置

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext", "WebWorker"],
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "module": "esnext",
    "jsx": "react-jsx",
    "types": ["cypress", "node", "cypress-real-events"],
  },
}

修复方法

  • 替换原生no-undef规则:原生ESLint的no-undef不支持识别TypeScript内置类型,改用@typescript-eslint提供的适配规则。在.eslintrc.js中添加规则配置:
    module.exports = {
      // ...原有配置
      rules: {
        "no-undef": "off",
        "@typescript-eslint/no-undef": "error"
      }
    };
    
  • 关联tsconfig到ESLint:在parserOptions中指定tsconfig路径,让ESLint能读取TypeScript的lib配置,确保DOM类型被正确识别:
    parserOptions: {
      // ...原有配置
      project: "./tsconfig.json"
    }
    

是否为@typescript-eslint的bug?

这不是bug。原生ESLint的no-undef规则针对JavaScript设计,无法处理TypeScript的全局类型定义;而@typescript-eslint插件提供的@typescript-eslint/no-undef规则是专为TypeScript场景打造的,能正确识别DOM等内置类型。问题出在你的配置未启用适配的TypeScript规则,导致原生规则误报。

内容的提问来源于stack exchange,提问作者ddblair

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 22:25:26