no-redeclare
不允许变量重新声明
在 配置文件 中使用来自 @eslint/js 的 recommended 配置可以启用此规则
在 JavaScript 中,可以使用 var 重新声明相同的变量名。这可能会导致混淆,因为不确定变量实际上是在何处声明和初始化的。
🌐 In JavaScript, it’s possible to redeclare the same variable name using var. This can lead to confusion as to where the variable is actually declared and initialized.
规则详情
🌐 Rule Details
此规则旨在消除在同一范围内具有多个声明的变量。
🌐 This rule is aimed at eliminating variables that have multiple declarations in the same scope.
此规则的错误代码示例:
🌐 Examples of incorrect code for this rule:
/*eslint no-redeclare: "error"*/
var a = 3;
var a = 10;
class C {
foo() {
var b = 3;
var b = 10;
}
static {
var c = 3;
var c = 10;
}
}
符合此规则的正确代码示例:
🌐 Examples of correct code for this rule:
/*eslint no-redeclare: "error"*/
var a = 3;
a = 10;
class C {
foo() {
var b = 3;
b = 10;
}
static {
var c = 3;
c = 10;
}
}
选项
🌐 Options
此规则接受一个可选参数,该参数是一个具有布尔属性 "builtinGlobals" 的对象。默认值为 true。如果设置为 true,此规则还会检查内置全局变量的重新声明,例如 Object、Array、Number…
🌐 This rule takes one optional argument, an object with a boolean property "builtinGlobals". It defaults to true.
If set to true, this rule also checks redeclaration of built-in globals, such as Object, Array, Number…
builtinGlobals
"builtinGlobals" 选项将检查全局作用域中内置全局变量的重新声明。
🌐 The "builtinGlobals" option will check for redeclaration of built-in globals in global scope.
针对 { "builtinGlobals": true } 选项的错误代码示例:
🌐 Examples of incorrect code for the { "builtinGlobals": true } option:
/*eslint no-redeclare: ["error", { "builtinGlobals": true }]*/
var Object = 0;
请注意,当使用 sourceType: "commonjs"(或使用默认解析器时的 ecmaFeatures.globalReturn)时,程序的最顶层作用域实际上不是全局作用域,而是“模块”作用域。在这种情况下,声明一个与内置全局变量同名的变量并不是重新声明,而是对全局变量的遮蔽。在这种情况下,应使用带有 "builtinGlobals" 选项的 no-shadow 规则。
🌐 Note that when using sourceType: "commonjs" (or ecmaFeatures.globalReturn, if using the default parser), the top scope of a program is not actually the global scope, but rather a “module” scope. When this is the case, declaring a variable named after a builtin global is not a redeclaration, but rather a shadowing of the global variable. In that case, the no-shadow rule with the "builtinGlobals" option should be used.
由 TypeScript 处理
使用 TypeScript 时禁用此规则是安全的,因为 TypeScript 的编译器强制执行此检查。
Note that while TypeScript will catch let redeclares and const redeclares, it will not catch var redeclares. Thus, if you use the legacy var keyword in your TypeScript codebase, this rule will still provide some value.
相关规则
版本
此规则是在 ESLint v0.0.9 中引入。