Generic Variadic Tuple Functions
You'll learn: How to write functions that accept and preserve tuple types with variable lengths using generics.
In standard JavaScript, you can write functions that accept any number of arguments. But in TypeScript, combining this flexibility with type safety — where the exact types and order of elements are preserved — requires a special pattern: generic variadic tuple functions.
The Core Idea
A variadic tuple function uses a generic type parameter constrained to any array (the variadic part) and preserves the exact tuple structure (types, order, and length) of what you pass in.
Think of it like a smart wrapper that remembers not just "you gave me items," but "you gave me exactly these three items in this specific order with these exact types."
The basic pattern:
function identity<T extends any[]>(...args: T): T {
return args;
}
Notice T extends any[] — this means "T can be any tuple or array type." When you call this function, TypeScript infers the exact tuple you passed:
const result = identity(42, "hello", true);
// result is [number, string, boolean], not (number | string | boolean)[]
Why This Matters
Without generics, you lose precision:
function badIdentity(...args: any[]) {
return args; // Returns any[], all type information lost
}
With the generic variadic pattern, you preserve everything — enabling type-safe function composition, argument forwarding, and utility functions.
Common Use Case: Prepending Elements
function prepend<T, U extends any[]>(first: T, ...rest: U): [T, ...U] {
return [first, ...rest];
}
const nums = prepend(1, "a", true);
// nums: [number, string, boolean]
Key Takeaway: Generic variadic tuple functions use T extends any[] with rest parameters to accept any tuple while preserving its exact type, length, and element order — enabling type-safe operations on variable-length argument lists.