no-unassigned-vars
禁止读取但从未赋值的 let
或 var
变量
此规则标记从未赋值但仍在代码中读取或使用的 let
或 var
声明。由于这些变量始终为 undefined
,因此它们的使用很可能是编程错误。
¥This rule flags let
or var
declarations that are never assigned a value but are still read or used in the code. Since these variables will always be undefined
, their usage is likely a programming mistake.
例如,如果你检查 status
变量的值,但该变量从未赋值,则它将始终为 undefined
:
¥For example, if you check the value of a status
variable, but it was never given a value, it will always be undefined
:
let status;
// ...forgot to assign a value to status...
if (status === 'ready') {
console.log('Ready!');
}
规则详情
¥Rule Details
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
/*eslint no-unassigned-vars: "error"*/
let status;
if (status === 'ready') {
console.log('Ready!');
}
let user;
greet(user);
function test() {
let error;
return error || "Unknown error";
}
let options;
const { debug } = options || {};
let flag;
while (!flag) {
// Do something...
}
let config;
function init() {
return config?.enabled;
}
在 TypeScript 中:
¥In TypeScript:
/*eslint no-unassigned-vars: "error"*/
let value: number | undefined;
console.log(value);
此规则的正确代码示例:
¥Examples of correct code for this rule:
/*eslint no-unassigned-vars: "error"*/
let message = "hello";
console.log(message);
let user;
user = getUser();
console.log(user.name);
let count;
count = 1;
count++;
// Variable is unused (should be reported by `no-unused-vars` only)
let temp;
let error;
if (somethingWentWrong) {
error = "Something went wrong";
}
console.log(error);
let item;
for (item of items) {
process(item);
}
let config;
function setup() {
config = { debug: true };
}
setup();
console.log(config);
let one = undefined;
if (one === two) {
// Noop
}
在 TypeScript 中:
¥In TypeScript:
/*eslint no-unassigned-vars: "error"*/
declare let value: number | undefined;
console.log(value);
何时不使用
¥When Not To Use It
如果你的代码有意使用已声明并使用但从未赋值的变量,则可以禁用此规则。以下情况可能适用:
¥You can disable this rule if your code intentionally uses variables that are declared and used, but are never assigned a value. This might be the case in:
-
使用未初始化变量作为占位符的旧代码库。
¥Legacy codebases where uninitialized variables are used as placeholders.
-
某些 TypeScript 用例中,变量声明时带有类型,但故意未赋值(尽管最好使用
declare
)。¥Certain TypeScript use cases where variables are declared with a type and intentionally left unassigned (though using
declare
is preferred).
相关规则
版本
此规则是在 ESLint v9.27.0 中引入。