跳至主要內容

dot-notation

盡可能強制使用點標記法。

🔧

此規則報告的一些問題可通過 --fix ESLint 命令列選項自動修復.

💭

此規則需要 類型資訊 才能執行。

此規則擴展了基本的 eslint/dot-notation 規則。它增加了

  • 支援可選擇性地忽略計算的 private 和/或 protected 成員存取。
  • 與 TypeScript 的 noPropertyAccessFromIndexSignature 選項相容。

如何使用

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

在 Playground 中試試這個規則 ↗

選項

請參閱 eslint/dot-notation 選項

此規則增加了以下選項

interface Options extends BaseDotNotationOptions {
allowPrivateClassPropertyAccess?: boolean;
allowProtectedClassPropertyAccess?: boolean;
allowIndexSignaturePropertyAccess?: boolean;
}

const defaultOptions: Options = {
...baseDotNotationDefaultOptions,
allowPrivateClassPropertyAccess: false,
allowProtectedClassPropertyAccess: false,
allowIndexSignaturePropertyAccess: false,
};

如果 TypeScript 編譯器選項 noPropertyAccessFromIndexSignature 設定為 true,則此規則始終允許使用方括號標記法來存取具有 string 索引簽章的類型的屬性,即使 allowIndexSignaturePropertyAccessfalse 也一樣。

allowPrivateClassPropertyAccess

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

class X {
private priv_prop = 123;
}

const x = new X();
x['priv_prop'] = 123;
在 Playground 中開啟

allowProtectedClassPropertyAccess

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

class X {
protected protected_prop = 123;
}

const x = new X();
x['protected_prop'] = 123;
在 Playground 中開啟

allowIndexSignaturePropertyAccess

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

class X {
[key: string]: number;
}

const x = new X();
x['hello'] = 123;
在 Playground 中開啟

如果 TypeScript 編譯器選項 noPropertyAccessFromIndexSignature 設定為 true,則始終允許上述程式碼,即使 allowIndexSignaturePropertyAccessfalse 也一樣。

何時不使用

如果您出於風格原因明確想要同時使用兩種成員存取類型,或者不希望強制使用一種風格,則可以避免使用此規則。

但是,請記住,不一致的風格可能會損害專案的可讀性。我們建議為此規則選擇最適合您專案的單一選項。


類型檢查的 lint 規則比傳統的 lint 規則更強大,但也需要設定 類型檢查的 linting。如果在啟用類型檢查規則後遇到效能下降的問題,請參閱 效能疑難排解

資源

滿懷 ❤️ 地從 ESLint 核心 中擷取。