一致的索引物件樣式
要求或拒絕使用
Record
屬性。
🎨
擴充 「plugin:@typescript-eslint/style"
在 ESLint 設定檔 裡啟用此規則。
🔧
有些此規則報的錯誤會自動修正,使用這指令: --fix
ESLint 命令列選項.
TypeScript 能定義任意物件 key 使用一個 index 特性. TypeScript 也有內建屬性名稱 Record
用來建一個僅定義一個 index 簽章的空物件. 例如, 下列屬性是相等的:
interface Foo {
[key: string]: unknown;
}
type Foo = {
[key: string]: unknown;
};
type Foo = Record<string, unknown>;
始終維持統一的宣告形式, 可以提升程式碼可讀性.
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/consistent-indexed-object-style": "error"
}
};
嘗試在操場上使用此規則 ↗
選項
此規則接受下列選項
type Options = ['index-signature' | 'record'];
const defaultOptions: Options = ['record'];
"record"
(預設): 只允許使用Record
屬性。"index-signature"
: 只允許使用 index 簽章。
record
- ❌ 錯誤
- ✅ 正確
index-signature
- ❌ 錯誤
- ✅ 正確
什麼時候不該使用
這個法則純粹是為了在專案中保持一致性的風格守則。如果你不想為索引物件類型保持一致的風格,便可以關閉此項。
不過,請記得,不一致的風格會降低專案的可讀性。我們建議為這個規則選取一個最適合專案的選項。