禁止未使用变量
注意:此规则是
recommended 规则集的一部分。在
deno.json 中启用完整集合{
"lint": {
"rules": {
"tags": ["recommended"]
}
}
}使用 Deno CLI 启用完整集合
deno lint --rules-tags=recommended
此规则可以通过将其添加到
deno.json 中的 include 或 exclude 数组中,来明确地包含或排除在当前标签的规则集中。{
"lint": {
"rules": {
"include": ["no-unused-vars"],
"exclude": ["no-unused-vars"]
}
}
}强制所有变量至少使用一次。
如果有变量已声明但未在任何地方使用,则很可能是由于不完整的重构造成的。此 lint 规则会检测并警告此类未使用的变量。
变量 a 在满足以下任一条件时被视为“已使用”:
- 它的值被读取,例如
console.log(a)或let otherVariable = a; - 它被调用或构造,例如
a()或new a() - 它被导出,例如
export const a = 42;
如果一个变量只是被赋值但从未被读取,那么它被认为是“未使用”的。
let a;
a = 42;
// `a` is never read out
如果您想有意地声明未使用的变量,请在它们前面加上下划线字符 _,例如 _a。此规则会忽略以 _ 为前缀的变量。
无效示例
const a = 0;
const b = 0; // this `b` is never used
function foo() {
const b = 1; // this `b` is used
console.log(b);
}
foo();
let c = 2;
c = 3;
// recursive function calls are not considered to be used, because only when `d`
// is called from outside the function body can we say that `d` is actually
// called after all.
function d() {
d();
}
// `x` is never used
export function e(x: number): number {
return 42;
}
const f = "unused variable";
有效示例
const a = 0;
console.log(a);
const b = 0;
function foo() {
const b = 1;
console.log(b);
}
foo();
console.log(b);
let c = 2;
c = 3;
console.log(c);
function d() {
d();
}
d();
export function e(x: number): number {
return x + 42;
}
export const f = "exported variable";