Course contentsShow
← TypeScript
Lesson 1390 of 1,79632. Advanced PatternsFree lesson

Extracting Parts of Variadic Tuples

Using infer with variadic tuples to extract head, tail, or middle sections of tuple types.

Extracting Parts of Variadic Tuples

You'll learn: How to use infer with variadic tuple types to extract specific portions like the head, tail, or middle sections of tuple types.

The Core Idea

Once you can work with variadic tuples (tuples with variable-length spreads), you often need to pull out specific pieces — like grabbing the first element, everything except the first, or slicing the middle. TypeScript's infer keyword lets you pattern-match on tuple structure and extract what you need.

Think of it like destructuring an array in JavaScript: const [first, ...rest] = arr. With types, you use infer in conditional types to capture those same parts at the type level.

Extracting the Head (First Element)

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

type Result1 = Head<[string, number, boolean]>; // string
type Result2 = Head<[]>; // never

The pattern [infer First, ...any[]] matches any tuple with at least one element, capturing the first into First.

Extracting the Tail (All But First)

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

type Result3 = Tail<[string, number, boolean]>; // [number, boolean]
type Result4 = Tail<[42]>; // []

Here, we discard the first element and capture everything else in Rest.

Extracting the Last Element

type Last<T extends any[]> = T extends [...any[], infer L] ? L : never;

type Result5 = Last<[1, 2, 3]>; // 3

Extracting Middle Sections

type DropFirstAndLast<T extends any[]> = 
  T extends [any, ...infer Middle, any] ? Middle : never;

type Result6 = DropFirstAndLast<[1, 2, 3, 4]>; // [2, 3]
type Result7 = DropFirstAndLast<[1, 2]>; // []

Multiple infer variables let you pattern-match complex structures.

Practical Use: Generic Function Utilities

type DropFirst<T extends any[]> = T extends [any, ...infer R] ? R : never;

// Type-safe function that drops first parameter
type RestParams<F extends (...args: any[]) => any> = 
  F extends (first: any, ...rest: infer R) => any ? R : never;

function log(msg: string, level: number, timestamp: Date) {}

type LogRest = RestParams<typeof log>; // [number, Date]

Key Takeaway: Combining infer with variadic tuple patterns lets you surgically extract head, tail, or middle portions of tuple types, enabling powerful type transformations for function signatures and data structures.