eslint/no-unused-vars 正確性
作用
禁止程式碼中未使用到的變數宣告、導入或型別宣告。
為何這是不好的?
在程式碼中宣告卻未被使用到的變數,很可能是由於不完整的重構所造成的錯誤。這些變數會佔用程式碼空間,並可能導致讀者混淆。
ts
// `b` is unused; this indicates a bug.
function add(a: number, b: number) {
return a;
}
console.log(add(1, 2));
如果符合以下任何一個條件,則變數 foo
會被視為已使用
- 它被呼叫 (
foo()
) 或建構 (new foo()
) - 它被讀取 (
var bar = foo
) - 它作為參數傳遞給函式或建構函式 (
doSomething(foo)
) - 它在傳遞給另一個函式的函式內部被讀取 (
doSomething(function() { foo(); })
) - 它被匯出 (
export const foo = 42
) - 它被用作 TypeScript
typeof
運算子的運算元 (const bar: typeof foo = 4
)
如果變數僅被宣告 (var foo = 5
) 或賦值 (foo = 7
),則該變數不被視為已使用。
型別
此規則完全支援 TypeScript 型別、介面、列舉和命名空間。
如果型別或介面 Foo
以任何下列方式使用,則會被視為已使用
- 它在另一個型別或介面的定義中使用。
- 它被用作型別註釋或函式簽章的一部分。
- 它在轉換或
satisfies
表達式中使用。
如果型別或介面僅在其自身的定義中使用,例如 type Foo = Array<Foo>
,則該型別或介面不被視為已使用。
列舉和命名空間的處理方式與變數、類別、函式等相同。
忽略的檔案
此規則會完全忽略 .d.ts
檔案和 .vue
檔案。在 .d.ts
檔案中宣告的變數、類別、介面和型別通常會被其他檔案使用,而這些檔案不會被 Oxlint 檢查。由於 Oxlint 不支援解析 Vue 範本,因此此規則無法判斷變數在 Vue 檔案中是否已使用。
已匯出
原始的 ESLint 規則會將 /* exported variableName */
註解識別為表示變數在另一個腳本中使用,不應被視為未使用的一種方式。由於 ES6 模組現在是 TC39 標準,因此 Oxlint 不支援此功能。
範例
此規則的不正確程式碼範例
javascript
/*eslint no-unused-vars: "error"*/
/*global some_unused_var*/
// It checks variables you have defined as global
some_unused_var = 42;
var x;
// Write-only variables are not considered as used.
var y = 10;
y = 5;
// A read for a modification of itself is not considered as used.
var z = 0;
z = z + 1;
// By default, unused arguments cause warnings.
(function (foo) {
return 5;
})();
// Unused recursive functions also cause warnings.
function fact(n) {
if (n < 2) return 1;
return n * fact(n - 1);
}
// When a function definition destructures an array, unused entries from
// the array also cause warnings.
function getY([x, y]) {
return y;
}
ts
type A = Array<A>;
enum Color {
Red,
Green,
Blue,
}
此規則的正確程式碼範例
js
/*eslint no-unused-vars: "error"*/
var x = 10;
alert(x);
// foo is considered used here
myFunc(
function foo() {
// ...
}.bind(this),
);
(function (foo) {
return foo;
})();
var myFunc;
myFunc = setTimeout(function () {
// myFunc is considered used
myFunc();
}, 50);
// Only the second argument from the destructured array is used.
function getY([, y]) {
return y;
}
ts
export const x = 1;
const y = 1;
export { y };
type A = Record<string, unknown>;
type B<T> = T extends Record<infer K, any> ? K : never;
const x = "foo" as B<A>;
console.log(x);
針對 /* exported variableName */
操作的不正確程式碼範例
js
/* exported global_var */
// Not respected, use ES6 modules instead.
var global_var = 42;