メインコンテンツにスキップ

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 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 } のコード例

type T = 'DeletedAt' | 'DeleteForever';
プレイグラウンドで開く

checkIntersections

交差型(&)をチェックするかどうか。

{ "checkIntersections": true } (デフォルト) のコード例

type ExampleIntersection = B & A;
プレイグラウンドで開く

checkUnions

共用体型(|)をチェックするかどうか。

{ "checkUnions": true } (デフォルト) のコード例

type ExampleUnion = B | A;
プレイグラウンドで開く

groupOrder

型の各構成要素はグループに配置され、ルールは各グループ内でアルファベット順にソートします。グループの順序はこのオプションによって決定されます。

  • conditional - 条件型 (A extends B ? C : D)
  • function - 関数型とコンストラクター型 (() => void, new () => type)
  • import - インポート型 (import('path'))
  • intersection - 交差型 (A & B)
  • keyword - キーワード型 (anystring など)
  • literal - リテラル型 (1'b'true など)
  • named - 名前付き型 (AA['prop']B[]Array<C>)
  • object - オブジェクト型 ({ a: string }{ [key: string]: number })
  • operator - 演算子型 (keyof Atypeof Breadonly C[])
  • tuple - タプル型 ([A, B, C])
  • union - 共用体型 (A | B)
  • nullish - nullundefined

例えば、ルールを { "groupOrder": ["literal", "nullish" ]} で設定すると

type ExampleGroup = null | 123;
プレイグラウンドで開く

使用しない場合

このルールは、プロジェクトの整合性を維持するための純粋にスタイルに関するルールです。交差型と共用体型の順序を一定かつ予測可能に保ちたくない場合は、このルールを無効にすることができます。ただし、一貫性のないスタイルはプロジェクトの可読性を損なう可能性があることに注意してください。

リソース