Course contentsShow
← TypeScript
Lesson 797 of 1,79618. Conditional TypesFree lesson

Extracting First and Last Tuple Elements

Using infer with tuple patterns like [infer First, ...any[]] to extract specific positions from tuple types.

Extracting First and Last Tuple Elements

You'll learn: How to use infer with specific tuple patterns to extract the first or last element from tuple types at compile time.


The Core Idea

Remember how infer lets you capture parts of types? When working with tuples, you can combine infer with tuple patterns to grab specific positions—like the first element, the last element, or anything in between.

Think of it like pattern matching: you describe what the tuple should look like (with some slots marked infer), and TypeScript fills in those slots with the actual types.


Extracting the First Element

To grab the first element, use the pattern [infer First, ...any[]]:

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

type A = GetFirst<[string, number, boolean]>;  // string
type B = GetFirst<[42]>;                        // 42 (literal type)
type C = GetFirst<[]>;                          // never (empty tuple)

What's happening: The pattern says "if this tuple has at least one element, capture that first element as First, and let the rest be anything."


Extracting the Last Element

For the last element, flip the pattern: [...any[], infer Last]:

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

type X = GetLast<[string, number, boolean]>;  // boolean
type Y = GetLast<[true]>;                      // true
type Z = GetLast<[]>;                          // never

The ...any[] matches "zero or more elements," so Last always captures whatever comes at the end.


Key Takeaway: Use [infer First, ...any[]] to extract the first tuple element and [...any[], infer Last] for the last—TypeScript's pattern matching with infer makes positional type extraction straightforward and type-safe.