Rest elements let you collect multiple values into one place inside a tuple. It helps when you want to handle many items without naming each one.
0
0
Rest elements in tuples in Typescript
Introduction
When you want to group some fixed values and then any number of extra values together.
When you need to pass a list of items but only care about the first few separately.
When you want to create flexible functions that accept tuples with varying lengths.
When you want to unpack parts of a tuple but keep the rest as a group.
Syntax
Typescript
type MyTuple = [string, ...number[]];
The ... before a type means 'rest element' that collects multiple items.
Rest elements must be last in the tuple.
Examples
This tuple starts with one string, then any number of strings after it.
Typescript
type Names = [string, ...string[]]; const group1: Names = ['Alice', 'Bob', 'Charlie']; const group2: Names = ['Dave'];
First two items are fixed types, then any number of strings can follow.
Typescript
type Data = [number, boolean, ...string[]]; const example: Data = [42, true, 'extra', 'values'];
You cannot put a rest element before the last item in a tuple.
Typescript
type Mixed = [...string[], number]; // Error: rest element must be lastSample Program
This program defines a tuple with a string, a number, and then any number of booleans. It shows two examples: one with extra booleans and one without.
Typescript
type Info = [string, number, ...boolean[]]; const person1: Info = ['John', 30, true, false]; const person2: Info = ['Jane', 25]; console.log(person1); console.log(person2);
OutputSuccess
Important Notes
Rest elements help keep tuples flexible and easy to work with.
Remember, rest elements must always be last in the tuple definition.
TypeScript checks the types of all elements, including those in the rest.
Summary
Rest elements collect multiple items into one part of a tuple.
They must be placed at the end of the tuple.
They make tuples flexible for different lengths of data.