跳至主要內容

類別方法使用 this

強制執行類別方法使用 this

此規則延伸基本 eslint/class-methods-use-this 規則。其新增支援忽略 override 方法或實作介面的類別上的方法。

如何使用

.eslintrc.cjs
module.exports = {
"rules": {
// Note: you must disable the base rule as it can report incorrect errors
"class-methods-use-this": "off",
"@typescript-eslint/class-methods-use-this": "error"
}
};

在遊樂場中嘗試此規則 ↗

選項

參閱 eslint/class-methods-use-this 選項

此規則新增下列選項

interface Options extends BaseClassMethodsUseThisOptions {
ignoreOverrideMethods?: boolean;
ignoreClassesThatImplementAnInterface?: boolean | 'public-fields';
}

const defaultOptions: Options = {
...baseClassMethodsUseThisOptions,
ignoreOverrideMethods: false,
ignoreClassesThatImplementAnInterface: false,
};

ignoreOverrideMethods

讓規則忽略任何明確標記為 override 的類別成員。

ignoreOverrideMethods 設為 true 時的正確程式碼範例

class X {
override method() {}
override property = () => {};
}
在 Playground 中開啟

ignoreClassesThatImplementAnInterface

使規則忽略在實作類型中定義的類別成員。如果有指定,可以為以下任一種

  • true:忽略實作介面的所有類別
  • 'public-fields':僅忽略實作介面的類別的公開欄位

請務必注意,此選項不僅適用於介面中定義的成員,因為那會需要類型資訊。

true

ignoreClassesThatImplementAnInterface 設為 true 時,正確程式碼範例

class X implements Y {
method() {}
property = () => {};
}
在 Playground 中開啟

'public-fields'

ignoreClassesThatImplementAnInterface 設為 'public-fields' 時,錯誤程式碼範例

class X implements Y {
method() {}
property = () => {};

private privateMethod() {}
private privateProperty = () => {};

protected privateMethod() {}
protected privateProperty = () => {};
}
在 Playground 中開啟

何時不使用

如果專案中動態的方式改變 this 範圍,而 TypeScript 難以建模,這個規則可能不適合使用。您可以考慮使用 ESLint disable 註解 來處理這些特定情況,而非完全停用此規則。

資源

ESLint core 摘錄。