no-redeclare

不允许变量重新声明

Recommended

配置文件 中使用来自 @eslint/jsrecommended 配置可以启用此规则

在 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,此规则还会检查内置全局变量的重新声明,例如 ObjectArrayNumber

¥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,如果使用默认解析器)时,程序的顶层作用域实际上不是全局作用域,而是 “module” 作用域。在这种情况下,声明一个以内置全局命名的变量不是重新声明,而是全局变量的影子。在这种情况下,应该使用带有 "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 的编译器强制执行此检查。

请注意,虽然 TypeScript 将捕获 let 重新声明和 const 重新声明,但它不会捕获 var 重新声明。因此,如果你在 TypeScript 代码库中使用旧版 var 关键字,此规则仍将提供一些值。

版本

此规则是在 ESLint v0.0.9 中引入。

资源

ESLint 中文网
粤ICP备13048890号