typescript / expert
Snippet
Recursive Tuple Reversal at the Type Level
Recursive conditional types combined with variadic tuple spreads let you compute on arrays at the type level — not just at the value level. `Reverse` splits the head off, recurses on the tail, and appends the head behind the reversed remainder. Paired with a `const` type parameter on the runtime helper, the inferred tuple stays literal (`[true, "a", 1]`) instead of widening to a union array, so call sites see precise positional types.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
type Reverse<T extends readonly unknown[]> =T extends readonly [infer H, ...infer R]? [...Reverse<R>, H]: [];type R1 = Reverse<[1, 2, 3]>;function reverseTuple<const T extends readonly unknown[]>(t: T): Reverse<T> {return [...t].reverse() as Reverse<T>;}const r = reverseTuple([1, "a", true] as const);
Breakdown
1
type Reverse<T extends readonly unknown[]> =
Generic type that maps a tuple to its reverse.
2
T extends readonly [infer H, ...infer R]
Extracts head H and rest R via variadic tuple inference.
3
? [...Reverse<R>, H]
Recursive case: reverse the tail then append the head.
4
function reverseTuple<const T extends readonly unknown[]>(t: T): Reverse<T> {
`const` parameter preserves literal positions; return type uses Reverse.