Course contentsShow
← TypeScript
Lesson 1458 of 1,79633. Inference Inversion PatternsFree lesson

Extracting Tuple First and Rest Elements

Use infer with tuple types to extract head elements or remaining tail tuple types.

Extracting Tuple First and Rest Elements

What you'll learn: How to use infer with tuple types to separate the first element from the remaining elements in a type-level operation.


When working with tuple types at the type level, you often need to split them apart—grabbing the first element and the rest, similar to how you might destructure an array in JavaScript. TypeScript's infer keyword in conditional types lets you do exactly this with tuple types.

The Head/Tail Pattern

Think of a tuple like a train: the first car (head) can be separated from all the remaining cars (tail). Using conditional types with infer, you can extract both pieces:

type First<T extends unknown[]> = T extends [infer Head, ...infer _]
  ? Head
  : never;

type Rest<T extends unknown[]> = T extends [infer _, ...infer Tail]
  ? Tail
  : never;

// Testing extraction
type Numbers = [1, 2, 3, 4];

type FirstNum = First<Numbers>;    // 1
type RestNums = Rest<Numbers>;     // [2, 3, 4]

type Letters = ['a', 'b'];
type FirstLetter = First<Letters>; // 'a'
type RestLetters = Rest<Letters>;  // ['b']

The pattern [infer Head, ...infer Tail] matches any tuple with at least one element. The first position is captured as Head, and ...infer Tail captures everything else as a new tuple.

Why This Matters

This extraction pattern is foundational for building recursive type operations on tuples. You can process tuples element-by-element, similar to recursive list processing in functional programming. For example, you might reverse a tuple, filter elements, or transform each element recursively.

Edge Cases

When a tuple has only one element, Rest returns an empty tuple [], not never. When a tuple is empty, both operations return never because the pattern doesn't match:

type SingleElement = [42];
type JustFirst = First<SingleElement>;  // 42
type JustRest = Rest<SingleElement>;    // []

type Empty = [];
type NoFirst = First<Empty>;  // never
type NoRest = Rest<Empty>;    // never

Key Takeaway: Use infer with tuple spread syntax ([infer Head, ...infer Tail]) to split tuples into first and rest elements, enabling powerful recursive type transformations on tuple types.