Indexing into Tuples with Generics
What you'll learn: How to use generic type parameters with indexed access to extract or manipulate specific element types from tuple types.
The Core Idea
When working with tuple types generically, you often need to extract the type of a specific element without knowing the exact tuple structure ahead of time. By combining generic constraints, tuple indexing, and TypeScript's indexed access type syntax (T[K]), you can write flexible, reusable type utilities that work with any tuple structure.
Think of it like writing a function that can retrieve an item from any shelf in any warehouse — you don't need to know the warehouse layout ahead of time, just how to navigate using the position you're given.
Basic Generic Tuple Indexing
The fundamental pattern combines a generic tuple type with a numeric index type:
function getAtIndex<T extends readonly unknown[], N extends number>(
tuple: T,
index: N
): T[N] {
return tuple[index];
}
const coords: [number, number, string] = [10, 20, "point"];
const x = getAtIndex(coords, 0); // Type: number
const label = getAtIndex(coords, 2); // Type: string
Here, T[N] performs indexed access into the tuple type, extracting the element type at position N.
Constraining the Index to Valid Positions
You can use keyof T to ensure the index is valid for the tuple:
function safeGet<T extends readonly unknown[], K extends keyof T>(
tuple: T,
key: K
): T[K] {
return tuple[key];
}
const triple: [boolean, string, number] = [true, "hello", 42];
const second = safeGet(triple, 1); // Type: string
// safeGet(triple, 5); // Error: Argument of type '5' not assignable
Extracting First and Last Elements
Using numeric literal types with generics:
type First<T extends readonly unknown[]> = T[0];
type Last<T extends readonly unknown[]> = T extends readonly [...unknown[], infer L]
? L
: never;
type Coords = [number, number, string];
type X = First<Coords>; // number
type Label = Last<Coords>; // string
Practical Pattern: Type-Safe Tuple Slice
type GetRange<
T extends readonly unknown[],
Start extends number,
End extends number
> = T extends readonly [...infer Prefix, ...infer Suffix]
? Prefix[Start] | Suffix[End]
: never;
// Extract multiple indices
type ElementAt<T extends readonly unknown[], N extends number> = T[N];
type Row = [string, number, boolean, Date];
type SecondCol = ElementAt<Row, 1>; // number
type ThirdCol = ElementAt<Row, 2>; // boolean
When This Pattern Shines
This technique is essential for building type-safe utilities that work with function parameter tuples, coordinate systems, database row types, or any structured data where position matters but the exact structure varies.
Key Takeaway: Combining generic constraints with indexed access (T[K]) lets you extract tuple element types dynamically, enabling type-safe operations on tuples of any shape or length.