# sort-union-types

Enforce sorted TypeScript union types.

Adhering to this rule ensures that union types are consistently sorted, resulting in cleaner and more maintainable code. By promoting a standardized ordering of union types, this rule makes it easier for developers to navigate and understand the structure of type unions within the codebase.

Consistently sorted union types enhance the overall clarity and organization of your code.

> **Important**
>
> If you use the [`sort-type-constituents`](https://typescript-eslint.io/rules/sort-type-constituents) rule from the [`@typescript-eslint/eslint-plugin`](https://typescript-eslint.io) plugin, it is highly recommended to [disable it](https://eslint.org/docs/latest/use/configure/rules#using-configuration-files-1) to avoid conflicts.

## Try it out

**Initial**

```tsx
type UserRole = 'user' | 'guest' | 'admin' | 'editor'

type ResponseStatus =
  | 'timeout'
  | 'success'
  | 'pending'
  | 'error'

type InputType =
  | 'password'
  | 'tel'
  | 'number'
  | 'text'
  | 'email'
```

**Sorted alphabetically**

```tsx
type UserRole = 'admin' | 'editor' | 'guest' | 'user'

type ResponseStatus =
  | 'error'
  | 'pending'
  | 'success'
  | 'timeout'

type InputType =
  | 'email'
  | 'number'
  | 'password'
  | 'tel'
  | 'text'
```

**Sorted by line length**

```tsx
type UserRole = 'editor' | 'admin' | 'guest' | 'user'

type ResponseStatus =
  | 'success'
  | 'pending'
  | 'timeout'
  | 'error'

type InputType =
  | 'password'
  | 'number'
  | 'email'
  | 'text'
  | 'tel'
```

## Options

This rule accepts an options object with the following properties:

### type

default: `'alphabetical'`

Specifies the sorting method.

- `'alphabetical'` — Sort items alphabetically (e.g., “a” \< “b” \< “c”) using [localeCompare](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare).
- `'natural'` — Sort items in a [natural](https://github.com/yobacca/natural-orderby) order (e.g., “item2” \< “item10”).
- `'line-length'` — Sort items by code line length (shorter lines first).
- `'custom'` — Sort items using the alphabet specified in the [`alphabet`](#alphabet) option.
- `'unsorted'` — Do not sort items. [`grouping`](#groups) and [`newlines behavior`](#newlinesbetween) are still enforced.

### order

default: `'asc'`

Specifies whether to sort items in ascending or descending order.

- `'asc'` — Sort items in ascending order (A to Z, 1 to 9).
- `'desc'` — Sort items in descending order (Z to A, 9 to 1).

### fallbackSort

type:

```ts
{
  type:
    | 'alphabetical'
    | 'natural'
    | 'line-length'
    | 'custom'
    | 'subgroup-order'
    | 'unsorted'
  order?: 'asc' | 'desc'
}
```

default: `{ type: 'unsorted' }`

Specifies fallback sort options for elements that are equal according to the primary sort [`type`](#type).

You can also sort by subgroup order (nested groups in the [`groups`](#groups) option) using `subgroup-order`.

Example: enforce alphabetical sort between two elements with the same length.

```ts
{
  type: 'line-length',
  order: 'desc',
  fallbackSort: { type: 'alphabetical', order: 'asc' }
}
```

### alphabet

default: `''`

Used only when the [`type`](#type) option is set to `'custom'`. Specifies the custom alphabet for sorting.

Use the `Alphabet` utility class from `eslint-plugin-perfectionist/alphabet` to quickly generate a custom alphabet.

Example: `0123456789abcdef...`

### ignoreCase

default: `true`

Specifies whether sorting should be case-sensitive.

- `true` — Ignore case when sorting alphabetically or naturally (e.g., “A” and “a” are the same).
- `false` — Consider case when sorting (e.g., “a” comes before “A”).

### specialCharacters

default: `'keep'`

Specifies whether to trim, remove, or keep special characters before sorting.

- `'keep'` — Keep special characters when sorting (e.g., “\_a” comes before “a”).
- `'trim'` — Trim special characters when sorting alphabetically or naturally (e.g., “\_a” and “a” are the same).
- `'remove'` — Remove special characters when sorting (e.g., “/a/b” and “ab” are the same).

### locales

default: `'en-US'`

Specifies the sorting locales. Refer To [String.prototype.localeCompare() - locales](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare#locales).

- `string` — A BCP 47 language tag (e.g. `'en'`, `'en-US'`, `'zh-CN'`).
- `string[]` — An array of BCP 47 language tags.

### partitionByComment

default: `false`

Enables the use of comments to separate the members of union types into logical groups. This can help in organizing and maintaining large union types by creating partitions based on comments.

- `true` — All comments will be treated as delimiters, creating partitions.
- `false` — Comments will not be used as delimiters.
- `RegExpPattern = string | { pattern: string; flags: string}` — A regexp pattern to specify which comments should act as delimiters.
- `RegExpPattern[]` — A list of regexp patterns to specify which comments should act as delimiters.
- `{ block: boolean | RegExpPattern | RegExpPattern[]; line: boolean | RegExpPattern | RegExpPattern[] }` — Specify which block and line comments should act as delimiters.

### partitionByNewLine

default: `false`

When `true`, the rule will not sort the members of an union type if there is an empty line between them. This helps maintain the defined order of logically separated groups of members.

```ts
type CarBrand =
  // Group 1
  Fiat |
  Honda |

  // Group 2
  Ferrari |

  // Group 3
  Chevrolet |
  Ford
```

Each group of union types (separated by empty lines) is treated independently, and the order within each group is preserved.

### newlinesBetween

type: `number | 'ignore'`

default: `'ignore'`

Specifies how to handle newlines between groups.

- `'ignore'` — Do not report errors related to newlines.
- `0` — No newlines are allowed.
- Any other number — Enforce this number of newlines between each group.

You can also enforce the newline behavior between two specific groups through the [`groups`](#newlines-between-groups)
option.

This option is only applicable when [`partitionByNewLine`](#partitionbynewline) is `false`.

### newlinesInside

type: `number | 'ignore' | 'newlinesBetween'`

default: `'newlinesBetween'`

Specifies how to handle newlines inside groups.

- `'ignore'` — Do not report errors related to newlines.
- `'newlinesBetween'` — \[DEPRECATED] If [`newlinesBetween`](#newlinesbetween) is `'ignore'`, then `'ignore'`, otherwise `0`.
- `0` — No newlines are allowed.
- Any other number — Enforce this number of newlines between each element of the same group.

You can also enforce the newline behavior inside a given group through the [`groups`](#group-with-overridden-settings)
or [`customGroups`](#customgroups) options.

This option is only applicable when [`partitionByNewLine`](#partitionbynewline) is `false`.

### useConfigurationIf

type:

```ts
{
  allNamesMatchPattern?:
    | string
    | string[]
    | { pattern: string; flags: string }
    | { pattern: string; flags: string }[]
  matchesAstSelector?: string
}
```

default: `{}`

Specifies filters to match a particular options configuration for a given union type.

The first matching options configuration will be used. If no configuration matches, the default options configuration will be used.

- `allNamesMatchPattern` — A regexp pattern that all union type members must match.

Example configuration:

```ts
{
  'perfectionist/sort-union-types': [
    'error',
    {
      groups: ['r', 'g', 'b'], // Sort colors by RGB
      customGroups: [
        {
          elementNamePattern: '^r$',
          groupName: 'r',
        },
        {
          elementNamePattern: '^g$',
          groupName: 'g',
        },
        {
          elementNamePattern: '^b$',
          groupName: 'b',
        },
      ],
      useConfigurationIf: {
        allNamesMatchPattern: '^[rgb]$',
      },
    },
    {
      type: 'alphabetical' // Fallback configuration
    }
  ],
}
```

- `matchesAstSelector` — An [AST selector](https://eslint.org/docs/latest/extend/selectors) matching a `TSUnionType` node.
  To avoid unexpected behavior, do not use `:exit` or `:enter` pseudo-selectors.

### groups

type:

```ts
  Array<
    | string
    | string[]
    | { newlinesBetween: number | 'ignore' }
    | {
        group: string | string[];
        type?: 'alphabetical' | 'natural' | 'line-length' | 'custom' | 'unsorted';
        order?: 'asc' | 'desc';
        fallbackSort?: { type: string; order?: 'asc' | 'desc' };
        newlinesInside?: number | 'ignore';
      }
  >
```

default: `[]`

Specifies a list of union type groups for sorting. Groups help organize types into categories, making your type definitions more readable and maintainable.

Each member will be assigned a single group specified in the `groups` option (or the `unknown` group if no match is found).
The order of items in the `groups` option determines how groups are ordered.

Within a given group, members will be sorted according to the `type`, `order`, `ignoreCase`, etc. options.

Individual groups can be combined together by placing them in an array. The order of groups in that array does not matter.
All members of the groups in the array will be sorted together as if they were part of a single group.

Predefined groups are characterized by a single selector.

##### Selectors

- `'conditional'` — Conditional types.
- `'function'` — Function types.
- `'import'` — Imported types.
- `'intersection'` — Intersection types.
- `'keyword'` — Keyword types.
- `'literal'` — Literal types.
- `'named'` — Named types.
- `'object'` — Object types.
- `'operator'` — Operator types.
- `'tuple'` — Tuple types.
- `'union'` — Union types.
- `'nullish'` — Nullish types (`null` or `undefined`).
- `'unknown'` — Types that don't fit into any group entered by the user.

##### The `unknown` group

Members that don't fit into any group specified in the `groups` option will be placed in the `unknown` group. If the `unknown` group is not specified in the `groups` option,
it will automatically be added to the end of the list.

#### Example 1

Using all selectors:

```ts
type Example =
  // 'conditional' — Conditional types.
  | (A extends B ? C : D)
  // 'function' — Function types.
  | ((arg: T) => U)
  // 'import' — Imported types.
  | import('module').Type
  // 'intersection' — Intersection types.
  | (A & B)
  // 'keyword' — Keyword types.
  | any
  // 'literal' — Literal types.
  | 'literal'
  | 42
  // 'named' — Named types.
  | SomeType
  | AnotherType
  // 'object' — Object types.
  | { a: string; b: number; }
  // 'operator' — Operator types.
  | keyof T
  // 'tuple' — Tuple types.
  | [string, number]
  // 'union' — Union types.
  | (A | B)
  // 'nullish' — Nullish types.
  | null
  | undefined;
```

`groups` option configuration:

```ts
{
  groups: [
    'conditional',
    'function',
    'import',
    'intersection',
    'keyword',
    'literal',
    'named',
    'object',
    'operator',
    'tuple',
    'union',
    'nullish',
  ]
}
```

#### Example 2

Combine and sort `intersection` and `union` groups together:

```ts
type Example =
  | AnotherType // 'named'
  | SomeType    // 'named'
  | (A & B)     // 'intersection'
  | (A | B)     // 'union'
  | (C & D)     // 'intersection'
  | (C | D)     // 'union'
  | keyof T;    // 'unknown'
```

`groups` option configuration:

```ts
{
  groups: [
    'named',
    ['intersection', 'union'],
    'unknown',
  ]
}
```

#### Group with overridden settings

You may directly override options for a specific group by using an object with the `group` property and other option overrides.

- `type` — Overrides the [`type`](#type) option for that group.
- `order` — Overrides the [`order`](#order) option for that group.
- `fallbackSort` — Overrides the [`fallbackSort`](#fallbacksort) option for that group.
- `newlinesInside` — Overrides the [`newlinesInside`](#newlinesinside) option for that group.

```ts
{
  groups: [
    'named',
    { group: 'literal', type: 'unsorted' }, // Elements from this group will not be sorted
  ]
}
```

#### Newlines between groups

You may place `newlinesBetween` objects between your groups to enforce the newline behavior between two specific groups.

See the [`newlinesBetween`](#newlinesbetween) option.

This feature is only applicable when [`partitionByNewLine`](#partitionbynewline) is `false`.

```ts
{
  newlinesBetween: 1,
  groups: [
    'a',
    { newlinesBetween: 0 }, // Overrides the global newlinesBetween option
    'b',
  ]
}
```

### customGroups

type: `Array<CustomGroupDefinition | CustomGroupAnyOfDefinition>`

default: `[]`

Defines custom groups to match specific union type members.

A custom group definition may follow one of the two following interfaces:

```ts
interface CustomGroupDefinition {
  groupName: string
  type?: 'alphabetical' | 'natural' | 'line-length' | 'unsorted'
  order?: 'asc' | 'desc'
  fallbackSort?: { type: string; order?: 'asc' | 'desc' }
  newlinesInside?: number | 'ignore'
  selector?: string
  elementNamePattern?: string | string[] | { pattern: string; flags?: string } | { pattern: string; flags?: string }[]
}
```

A type member will match a `CustomGroupDefinition` group if it matches all the filters of the custom group's definition.

or:

```ts
interface CustomGroupAnyOfDefinition {
  groupName: string
  type?: 'alphabetical' | 'natural' | 'line-length' | 'unsorted'
  order?: 'asc' | 'desc'
  fallbackSort?: { type: string; order?: 'asc' | 'desc' }
  newlinesInside?: number | 'ignore'
  anyOf: Array<{
      selector?: string
      elementNamePattern?: string | string[] | { pattern: string; flags?: string } | { pattern: string; flags?: string }[]
  }>
}
```

A type member will match a `CustomGroupAnyOfDefinition` group if it matches all the filters of at least one of the `anyOf` items.

#### Attributes

- `groupName` — The group's name, which needs to be put in the [`groups`](#groups) option.
- `selector` — Filter on the `selector` of the element.
- `elementNamePattern` — If entered, will check that the name of the element matches the pattern entered.
- `type` — Overrides the [`type`](#type) option for that custom group.
- `order` — Overrides the [`order`](#order) option for that custom group.
- `fallbackSort` — Overrides the [`fallbackSort`](#fallbacksort) option for that custom group.
- `newlinesInside` — Overrides the [`newlinesInside`](#newlinesinside) option for that custom group.

#### Match importance

The `customGroups` list is ordered:
The first custom group definition that matches an element will be used.

Custom groups have a higher priority than any predefined group.

## Usage

**Flat Config**

```tsx
// eslint.config.js
import perfectionist from 'eslint-plugin-perfectionist'

export default [
  {
    plugins: {
      perfectionist,
    },
    rules: {
      'perfectionist/sort-union-types': [
        'error',
        {
          type: 'alphabetical',
          order: 'asc',
          fallbackSort: { type: 'unsorted' },
          ignoreCase: true,
          specialCharacters: 'keep',
          partitionByComment: false,
          partitionByNewLine: false,
          newlinesBetween: 'ignore',
          newlinesInside: 'ignore',
          useConfigurationIf: {},
          groups: [],
          customGroups: [],
        },
      ],
    },
  },
]
```

**Legacy Config**

```tsx
// .eslintrc.js
module.exports = {
  plugins: [
    'perfectionist',
  ],
  rules: {
    'perfectionist/sort-union-types': [
      'error',
      {
        type: 'alphabetical',
        order: 'asc',
        fallbackSort: { type: 'unsorted' },
        ignoreCase: true,
        specialCharacters: 'keep',
        partitionByComment: false,
        partitionByNewLine: false,
        newlinesBetween: 'ignore',
        newlinesInside: 'ignore',
        groups: [],
        customGroups: [],
      },
    ],
  },
}
```

## Version

This rule was introduced in [v0.4.0](https://github.com/azat-io/eslint-plugin-perfectionist/releases/tag/v0.4.0).

## Resources

- [Rule source](https://github.com/azat-io/eslint-plugin-perfectionist/blob/main/rules/sort-union-types.ts)
- [Test source](https://github.com/azat-io/eslint-plugin-perfectionist/blob/main/test/rules/sort-union-types.test.ts)
