Tuple Type Utilities: First and Last
What you'll learn: How to build reusable utility types that extract the first or last element type from a tuple at compile time.
When working with tuples, you often need to reference specific positions — particularly the first or last element. Instead of repeatedly writing index access types like MyTuple[0], you can create generic utilities that work with any tuple.
Building the First Utility
The First utility extracts the type of the first element:
type First<T extends readonly unknown[]> = T extends [infer F, ...unknown[]]
? F
: never;
This uses a conditional type with infer to capture the first element. If the tuple matches the pattern [first, ...rest], we extract and return the first element's type. Otherwise, we return never for empty tuples.
Usage example:
type Names = ["Alice", "Bob", "Charlie"];
type FirstName = First<Names>; // "Alice"
type Numbers = [1, 2, 3];
type FirstNum = First<Numbers>; // 1
type Empty = [];
type NoFirst = First<Empty>; // never
Building the Last Utility
The Last utility extracts the final element type:
type Last<T extends readonly unknown[]> = T extends [...unknown[], infer L]
? L
: never;
The pattern [...rest, last] lets us capture the last element while ignoring everything before it.
Usage example:
type Names = ["Alice", "Bob", "Charlie"];
type LastName = Last<Names>; // "Charlie"
type Mixed = [string, number, boolean];
type LastType = Last<Mixed>; // boolean
These utilities shine when building higher-level type transformations or when working with function parameters as tuples.
Key Takeaway: Use conditional types with infer and rest element patterns to extract first ([infer F, ...unknown[]]) or last ([...unknown[], infer L]) tuple element types cleanly.