Rest Elements in Tuples
What you'll learn: How to use rest elements to capture variable-length segments within tuple types, enabling flexible yet type-safe tuple patterns.
The Problem: Fixed-Length Tuples Don't Always Cut It
You've learned that tuples have fixed positions with specific types. But sometimes you need a tuple where most positions are known, but then there's a variable number of additional elements at the end (or beginning). That's where rest elements shine.
What Are Rest Elements in Tuples?
A rest element in a tuple type uses the ... syntax (just like JavaScript rest parameters) to capture any number of remaining elements into an array type. Think of it like saying: "The first two elements are specific types, and then... whatever else follows, as long as they're all numbers."
Basic Syntax
type MyTuple = [string, number, ...boolean[]];
const valid: MyTuple = ["hello", 42, true, false, true];
const alsoValid: MyTuple = ["hello", 42]; // Zero booleans is fine
const stillValid: MyTuple = ["hello", 42, false]; // One boolean
The ...boolean[] means "zero or more booleans after the first two elements."
Rest Elements Can Appear at Different Positions
// At the end
type EndRest = [string, ...number[]];
// At the beginning
type StartRest = [...string[], number];
// In the middle (with other elements after)
type MiddleRest = [boolean, ...string[], number];
Each pattern lets you enforce type safety where it matters while allowing flexibility where you need it.
Practical Use Case
type LogEntry = [timestamp: number, level: string, ...details: string[]];
const log1: LogEntry = [Date.now(), "ERROR", "Database connection failed"];
const log2: LogEntry = [Date.now(), "INFO", "User logged in", "userId: 123", "ip: 192.168.1.1"];
Key Takeaway: Rest elements in tuples let you combine the precision of fixed-position types with the flexibility of variable-length arrays, creating hybrid structures that are both type-safe and adaptable to real-world data patterns.