infer in Tuple Positions
You'll learn how to use infer to extract specific elements from tuple types, including first, last, and middle positions.
Now that you've seen infer extract types from arrays, functions, and nested structures, it's time to see how it works with specific positions in tuples. Tuples have fixed lengths and types at each index, which makes them perfect targets for positional extraction.
The Core Idea
When you use infer with tuple types, you can pattern-match against specific positions. Think of it like destructuring an array in JavaScript, but at the type level. You can grab the first element, the last element, or even elements from the middle by using rest elements (...) to skip over parts you don't care about.
Extracting the First Element
type First<T extends any[]> = T extends [infer F, ...any[]] ? F : never;
type A = First<[string, number, boolean]>; // string
type B = First<[42]>; // 42
type C = First<[]>; // never
The pattern [infer F, ...any[]] means: "If this tuple has at least one element, capture the first one as F."
Extracting the Last Element
type Last<T extends any[]> = T extends [...any[], infer L] ? L : never;
type D = Last<[string, number, boolean]>; // boolean
type E = Last<[42]>; // 42
type F = Last<[]>; // never
Here, [...any[], infer L] means: "Match any number of leading elements, then capture the last one as L."
Extracting Middle Elements
type Second<T extends any[]> = T extends [any, infer S, ...any[]] ? S : never;
type G = Second<[string, number, boolean]>; // number
type H = Second<[1, 2]>; // 2
type I = Second<[1]>; // never
You can extend this pattern to extract any position by adjusting where you place infer and any.
Key Takeaway: infer in tuple positions lets you pattern-match and extract types from specific indices, enabling precise type-level tuple manipulation without runtime code.