版本

no-const-assign

禁止重新分配 const 变量

推荐

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

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

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

规则详情

此规则旨在标记修改使用 const 关键字声明的变量。

此规则的错误代码示例

在 Playground 中打开
/*eslint no-const-assign: "error"*/

const a = 0;
a = 1;
在 Playground 中打开
/*eslint no-const-assign: "error"*/

const a = 0;
a += 1;
在 Playground 中打开
/*eslint no-const-assign: "error"*/

const a = 0;
++a;

此规则的正确代码示例

在 Playground 中打开
/*eslint no-const-assign: "error"*/

const a = 0;
console.log(a);
在 Playground 中打开
/*eslint no-const-assign: "error"*/

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

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

何时不使用

如果您不想收到关于修改使用 const 关键字声明的变量的通知,您可以安全地禁用此规则。

由 TypeScript 处理

当使用 TypeScript 时,禁用此规则是安全的,因为 TypeScript 的编译器会强制执行此检查。

版本

此规则在 ESLint v1.0.0-rc-1 中引入。

资源

更改语言