no-const-assign

禁止重新分配 constusingawait using 变量

Recommended

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

常量绑定无法修改。尝试修改常量绑定将引发运行时错误。

¥Constant bindings cannot be modified. An attempt to modify a constant binding will raise a runtime error.

规则详情

¥Rule Details

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

¥This rule is aimed to flag modifying variables that are declared using const, using, or await using keywords.

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

在线运行
/*eslint no-const-assign: "error"*/

const a = 0;
a = 1;
在线运行
/*eslint no-const-assign: "error"*/

const a = 0;
a += 1;
在线运行
/*eslint no-const-assign: "error"*/

const a = 0;
++a;
在线运行
/*eslint no-const-assign: "error"*/

if (foo) {
	using a = getSomething();
	a = somethingElse;
}

if (bar) {
	await using a = getSomething();
	a = somethingElse;
}

此规则的正确代码示例:

¥Examples of correct code for this rule:

在线运行
/*eslint no-const-assign: "error"*/

const a = 0;
console.log(a);
在线运行
/*eslint no-const-assign: "error"*/

if (foo) {
	using a = getSomething();
	a.execute();
}

if (bar) {
	await using a = getSomething();
	a.execute();
}
在线运行
/*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);
}
在线运行
/*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);
}

何时不使用

¥When Not To Use It

如果你不想在修改使用 constusingawait using 关键字声明的变量时收到通知,可以安全地禁用此规则。

¥If you don’t want to be notified about modifying variables that are declared using const, using, and await using keywords, you can safely disable this rule.

由 TypeScript 处理

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

版本

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

资源