Skip to main content

prefer-type-fest-union-length

Require TypeFest UnionLength over UnionToTuple<T>['length'].

Targeted pattern scopeโ€‹

This rule reports UnionToTuple<T>['length'] indexed-access type patterns and prefers the canonical UnionLength<T> from type-fest, which encapsulates the same intent with less visual noise.

What this rule reportsโ€‹

  • TSIndexedAccessType nodes of the shape UnionToTuple<T>['length'].

Detection boundariesโ€‹

  • โœ… Reports UnionToTuple<T>['length'] with exactly one type argument forwarded.
  • โœ… Autofixes by replacing the indexed-access type with UnionLength<T> and inserting a type-fest import when absent.
  • โŒ Does not auto-fix where the UnionLength identifier is shadowed by a type parameter in scope.
  • โŒ Does not flag UnionToTuple<T>[0] or other non-'length' index expressions.
  • โŒ Does not flag UnionToTuple<T> used without an index type.

Why this rule existsโ€‹

UnionLength<T> is the canonical TypeFest utility for computing the number of members in a union type.

The pattern UnionToTuple<T>['length'] is functionally equivalent but requires two chained operations and knowledge that UnionToTuple produces a tuple. Using the dedicated UnionLength<T> utility is more declarative, easier to read, and signals intent without requiring knowledge of the intermediate tuple form.

โŒ Incorrectโ€‹

type ColorCount = UnionToTuple<Colors>['length'];

โœ… Correctโ€‹

import type { UnionLength } from "type-fest";

type ColorCount = UnionLength<Colors>;

Behavior and migration notesโ€‹

  • UnionLength<T> returns the numeric literal type representing the number of members in the union T.
  • Both UnionToTuple<T>['length'] and UnionLength<T> are structurally equivalent โ€” the autofix is safe.
  • The type argument forwarded to UnionLength<T> is taken directly from UnionToTuple<T>.

ESLint flat config exampleโ€‹

import typefest from "eslint-plugin-typefest";

export default [
{
plugins: { typefest },
rules: {
"typefest/prefer-type-fest-union-length": "error",
},
},
];

When not to use itโ€‹

Disable this rule if your codebase uses UnionToTuple<T>['length'] intentionally for clarity (e.g., in tightly-scoped local type algebra where both operations are discussed together).

Package documentationโ€‹

TypeFest package documentation:

Source file: source/union-length.d.ts

/**
Get the number of elements in a union type.

@example
```
import type {UnionLength} from 'type-fest';

type Colors = 'red' | 'green' | 'blue';
type Count = UnionLength<Colors>;
//=> 3
```

@category Union
@category Numeric
*/

Rule catalog ID: R099

Further readingโ€‹

Adoption resourcesโ€‹