sort-type-constituents
強制執行類型聯合/交集的組成須按照字母順序排列。
🔧
某些這個規則報告的問題可由 --fix
ESLint 命令列選項自動修正.
💡
某些這個規則報告的問題可由編輯器 提出建議後手動修正.
已棄用
對聯盟 (|
) 和交集 (&
) 類型進行排序有助於
- 保持程式碼庫標準化
- 找出重複的類型
- 減少版本差異混亂
此規則會針對任何未按字母順序排序的類型提出報告。
類型以不區分大小寫的方式排序,並類似人類對數字的處理方式,若出現相等情況則改用字元碼排序。
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/sort-type-constituents": "error"
}
};
在遊樂場試用此規則↗
範例
- ❌錯誤
- ✅正確
type T1 = B | A;
type T2 = { b: string } & { a: string };
type T3 = [1, 2, 4] & [1, 2, 3];
type T4 =
| [1, 2, 4]
| [1, 2, 3]
| { b: string }
| { a: string }
| (() => void)
| (() => string)
| 'b'
| 'a'
| 'b'
| 'a'
| readonly string[]
| readonly number[]
| string[]
| number[]
| B
| A
| string
| any;
在遊樂場中開啟type T1 = A | B;
type T2 = { a: string } & { b: string };
type T3 = [1, 2, 3] & [1, 2, 4];
type T4 =
| A
| B
| number[]
| string[]
| any
| string
| readonly number[]
| readonly string[]
| 'a'
| 'a'
| 'b'
| 'b'
| (() => string)
| (() => void)
| { a: string }
| { b: string }
| [1, 2, 3]
| [1, 2, 4];
在遊樂場中開啟選項
此規則接受以下選項
type Options = [
{
/** Whether to sort using case sensitive sorting. */
caseSensitive?: boolean;
/** Whether to check intersection types. */
checkIntersections?: boolean;
/** Whether to check union types. */
checkUnions?: boolean;
/** Ordering of the groups. */
groupOrder?: (
| 'conditional'
| 'function'
| 'import'
| 'intersection'
| 'keyword'
| 'literal'
| 'named'
| 'nullish'
| 'object'
| 'operator'
| 'tuple'
| 'union'
)[];
},
];
const defaultOptions: Options = [
{
checkIntersections: true,
checkUnions: true,
caseSensitive: false,
groupOrder: [
'named',
'keyword',
'operator',
'literal',
'function',
'import',
'conditional',
'object',
'tuple',
'intersection',
'union',
'nullish',
],
},
];
caseSensitive
是否使用區分大小寫的字串比對進行排序。
使用 { "caseSensitive": true }
程式碼範例
checkIntersections
是否檢查交集類型 (&
)。
使用 { "checkIntersections": true }
(預設值) 的程式碼範例
checkUnions
是否檢查聯盟類型 (|
)。
使用 { "checkUnions": true }
(預設值) 的程式碼範例
groupOrder
類型的每個組成部分都會放入群組中,然後規則會在每個群組中按字母順序排序。群組的順序由這個選項決定。
conditional
- 條件類型 (A extends B ? C : D
)function
- 函式和建構函式類型 (() => void
,new () => type
)import
- 匯入類型 (import('path')
)intersection
- 交集類型 (A & B
)keyword
- 關鍵字類型 (any
,string
等)literal
- 文字類型 (1
,'b'
,true
等)named
- 命名類型 (A
,A['prop']
,B[]
,Array<C>
)物件
- 物件類型({ a: 字串 }
、{ [key: 字串]: 數字 }
)運算子
- 運算子類型(keyof A
、typeof B
、readonly C[]
)陣列
- 陣列類型([A, B, C]
)聯合
- 聯合計錄(A | B
)nullish
-null
和undefined
例如,使用 { "groupOrder": ["文字", "nullish" ]}
設定規則
什麼時候不使用
此規則純粹是維持專案一致性的風格規則。如果您不希望交集和聯合類型維持一致且可預測的順序,您可以把它關閉。不過,請謹記,不一致的風格可能會損害專案的可讀性。