TypeScript Snippet

Fixed-Length Tuple via Generics

Difficulty: Medium

Constraining an argument to 'an array of exactly 4 numbers' is a common need (RGBA, 4x4 matrices, fixed-length feature vectors). TypeScript can express it with a recursive `TupleOf<T, N>` that builds up `[T, T, T, ...]` of the requested length. This snippet covers the recursive construction, a runtime helper that produces a value matching the type, and a length-comparison variant useful for richer constraints ("at least N", "between N and M").

Code Snippets
/

Fixed-Length Tuple via Generics

Fixed-Length Tuple via Generics

Constraining an argument to 'an array of exactly 4 numbers' is a common need (RGBA, 4x4 matrices, fixed-length feature vectors). TypeScript can express it with a recursive `TupleOf<T, N>` that builds up `[T, T, T, ...]` of the requested length. This snippet covers the recursive construction, a runtime helper that produces a value matching the type, and a length-comparison variant useful for richer constraints ("at least N", "between N and M").

TypeScript
Medium
3 snippets
ts-utility-types
ts-conditional-types
ts-generics
code-template

562 views

15

The recursion builds R (an array accumulator type) one element at a time and stops when R['length'] matches N. TypeScript treats tuple length as a numeric literal when the tuple is fully known, which is what makes this comparison possible at the type level. The default R extends T[] = [] lets callers write TupleOf<T, N> without supplying the accumulator. The technique is the building block for every length-aware utility (split, join, take, drop) in advanced TS libraries; understanding it unlocks the rest.