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

如何检测子作用域中重复声明的同名变量?ESLint规则咨询

检测子作用域同名变量重复声明的ESLint规则
  • 你需要的是ESLint的no-shadow规则,它专门用于禁止在子作用域中声明与父作用域同名的变量,正好解决你提到的场景问题。no-redeclare规则仅检测同一作用域内的重复声明,所以无法覆盖跨作用域的情况。

规则作用示例

针对你提供的代码:

{
  const myVar = "ok"
  if (true)
  {
    //should give warning because myVar already declared in parent scope
    const myVar = "not ok";
    console.log(myVar);
  }
  console.log(myVar);
}

启用no-shadow规则后,ESLint会提示'myVar' is already declared in the upper scope(或类似提示),标记子作用域内的myVar声明为问题。

配置方式

在你的ESLint配置文件(如.eslintrc.js或.eslintrc.json)中添加或修改规则:

{
  "rules": {
    "no-shadow": "warn" // 或 "error",根据需求设置级别
  }
}

可选自定义配置

如果需要允许特定变量在子作用域被重新声明,可以添加规则选项:

{
  "rules": {
    "no-shadow": [
      "warn",
      {
        "allow": ["err", "res"] // 允许这些变量在子作用域重新声明
      }
    ]
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 17:43:10