Versions

no-const-assign

Disallow reassigning const variables

Recommended

The "extends": "eslint:recommended" property in a configuration file enables this rule

我们不能修改使用 const 关键字声明的变量。 它将引发运行时错误。

在非 ES2015 环境下,它可能仅仅被忽略。

规则细节

这条规则的目的是标记修改使用 const 关键字声明的变量。

使用此规则的错误示例:

Open in Playground
/*eslint no-const-assign: "error"*/
/*eslint-env es6*/

const a = 0;
a = 1;
Open in Playground
/*eslint no-const-assign: "error"*/
/*eslint-env es6*/

const a = 0;
a += 1;
Open in Playground
/*eslint no-const-assign: "error"*/
/*eslint-env es6*/

const a = 0;
++a;

使用此规则的正确示例:

Open in Playground
/*eslint no-const-assign: "error"*/
/*eslint-env es6*/

const a = 0;
console.log(a);
Open in Playground
/*eslint no-const-assign: "error"*/
/*eslint-env es6*/

for (const a in [1, 2, 3]) { // `a` is re-defined (not modified) on each loop step.
    console.log(a);
}
Open in Playground
/*eslint no-const-assign: "error"*/
/*eslint-env es6*/

for (const a of [1, 2, 3]) { // `a` is re-defined (not modified) on each loop step.
    console.log(a);
}

何时不用

如果你不关心使用 const 关键字声明的变量是否被修改,你可以安全地禁用这个规则。

Handled by TypeScript

It is safe to disable this rule when using TypeScript because TypeScript's compiler enforces this check.

Version

This rule was introduced in ESLint v1.0.0-rc-1.

Resources

更改语言