Course contentsShow
← TypeScript
Lesson 121 of 1,7963. Basic TypesFree lesson

Rest Elements in Tuples

Use rest syntax for variable-length tails: [string, ...number[]] accepts one string followed by any number of numbers.

What You'll Learn

You'll learn how to use rest syntax in tuples to accept a fixed set of elements followed by any number of additional elements of a specific type.

The Core Idea

So far, you've seen tuples with exact, fixed lengths like [string, number]. But sometimes you need a tuple that starts with specific types and then accepts as many additional elements as needed at the end. That's where rest elements come in.

A rest element uses the ... syntax (just like rest parameters in arrays) and must come at the end of the tuple. It captures all remaining elements into an array of a specific type.

The Syntax

type MixedTuple = [string, ...number[]];

This declares a tuple that:

  • Must have a string as the first element
  • Can have zero or more number elements after that

Using Rest Element Tuples

type NameAndScores = [string, ...number[]];

const student1: NameAndScores = ["Alice", 95, 88, 92];
const student2: NameAndScores = ["Bob", 78];
const student3: NameAndScores = ["Carol"]; // OK - zero scores is valid

All three are valid because after the required string, any amount of number elements is acceptable.

Analogy

Think of it like a sign-up form: "Name (required), followed by any number of phone numbers (optional)." The first field is mandatory, but you can add as many phone numbers as you want afterward—or none at all.

What You Cannot Do

The rest element must be last:

type Invalid = [...string[], number]; // Error! Rest must come last

Key Takeaway: Rest elements in tuples ([string, ...number[]]) let you define a fixed "head" followed by a variable-length "tail" of a specific type, giving you flexibility while maintaining type safety.