How would you use conditional types together with tuples to implement a type-safe 'head' and 'tail' extraction, similar to array destructuring at the type level?
Short answer
Use conditional types with 'infer' to pattern-match a tuple's shape into its first element and the remaining elements as a separate tuple — mirroring how `const [first, ...rest] = arr` works at runtime, but entirely at the type level for use in other generic type utilities.
Advertisement
AModel answer
Use conditional types with 'infer' to pattern-match a tuple's shape into its first element and the remaining elements as a separate tuple — mirroring how `const [first, ...rest] = arr` works at runtime, but entirely at the type level for use in other generic type utilities.
type Head<T extends unknown[]> = T extends [infer First, ...unknown[]] ? First : never;
type Tail<T extends unknown[]> = T extends [unknown, ...infer Rest] ? Rest : [];
type H = Head<[string, number, boolean]>; // string
type Tl = Tail<[string, number, boolean]>; // [number, boolean]Real-world example
Building advanced generic utilities (like a type-level recursive curry or compose function) that need to process a tuple one element at a time.
Likely follow-ups
- How would you combine Head and Tail recursively to build a type-level 'reverse' utility for a tuple?
Related topics