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โ
TSIndexedAccessTypenodes of the shapeUnionToTuple<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 atype-festimport when absent. - โ Does not auto-fix where the
UnionLengthidentifier 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 unionT.- Both
UnionToTuple<T>['length']andUnionLength<T>are structurally equivalent โ the autofix is safe. - The type argument forwarded to
UnionLength<T>is taken directly fromUnionToTuple<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