Course contentsShow
← TypeScript
Lesson 1388 of 1,79632. Advanced PatternsFree lesson

Prepending and Appending to Tuples

Adding fixed elements before or after variadic sections to build composite tuple types.

Prepending and Appending to Tuples

You'll learn how to add fixed elements before or after variadic sections to build composite tuple types that preserve type information throughout.

The Core Idea

When working with variadic tuple types, you often need to attach additional fixed elements at the beginning or end. Think of it like bookending a flexible sequence: you might want every tuple to start with a status code, end with a timestamp, or both — while keeping the middle section variable.

TypeScript lets you combine fixed tuple elements with variadic rest elements using spread syntax, giving you precise control over composite tuple shapes.

Basic Prepending Pattern

type Prepend<T extends unknown[], U> = [U, ...T];

type Original = [string, number];
type WithPrefix = Prepend<Original, boolean>;
// type WithPrefix = [boolean, string, number]

The spread operator ...T expands the original tuple, and placing U before it creates a new tuple with the element prepended.

Basic Appending Pattern

type Append<T extends unknown[], U> = [...T, U];

type Original = [string, number];
type WithSuffix = Append<Original, boolean>;
// type WithSuffix = [string, number, boolean]

Here, the spread comes first, followed by the new element, effectively adding it to the end.

Combining Both Operations

type Wrap<T extends unknown[], Prefix, Suffix> = [Prefix, ...T, Suffix];

type Core = [string, number];
type Wrapped = Wrap<Core, boolean, symbol>;
// type Wrapped = [boolean, string, number, symbol]

This pattern is powerful for adding metadata, headers, or footers to tuple-based data structures while preserving the inner variadic content.

Real-World Use Case

type ApiResponse<T extends unknown[]> = [status: number, ...data: T, timestamp: Date];

type UserResponse = ApiResponse<[name: string, age: number]>;
// type UserResponse = [status: number, name: string, age: number, timestamp: Date]

Key Takeaway: Prepending and appending let you construct composite tuples by placing fixed elements before or after variadic sections, enabling type-safe wrappers that preserve inner tuple structure while adding consistent metadata or markers.