typescript / expert
Snippet
Variadic Tuple Types for Functional Composition
Variadic tuple types allow us to capture and manipulate the shape of arrays and arguments with precision. Using the spread operator within tuple types enables recursive operations on function parameters, vital for high-level functional programming.
snippet.ts
1
2
3
4
5
6
7
8
9
10
type Last<T extends any[]> = T extends [...any, infer L] ? L : never;type Shift<T extends any[]> = T extends [any, ...infer R] ? R : never;function tail<T extends any[]>(arr: [...T]): Shift<T> {const [_, ...rest] = arr;return rest as Shift<T>;}const tuple = [1, "hello", true] as const;const result = tail(tuple); // ["hello", true]
Breakdown
1
T extends [...any, infer L]
Uses spread at the start to capture all elements except the last one, which is inferred as 'L'.
2
[...T]
A variadic tuple spread that preserves the exact literal values and order if the input is a 'const' array.