Advertisement
Intermediate TypeScript, Primitive Types, Arrays & Tuples

How does a rest element work within a tuple type, like `[string, ...number[]]`?

Short answer

A tuple can end with a rest element (using '...Type[]') to require a FIXED set of leading elements of specific types, followed by any number (including zero) of additional elements all sharing the rest element's type — combining tuple precision with array flexibility.

Save TypeScript mock interview
Advertisement
AModel answer
A tuple can end with a rest element (using '...Type[]') to require a FIXED set of leading elements of specific types, followed by any number (including zero) of additional elements all sharing the rest element's type — combining tuple precision with array flexibility.
type StringThenNumbers = [string, ...number[]];
const a: StringThenNumbers = ['label'];           // OK, zero numbers
const b: StringThenNumbers = ['label', 1, 2, 3];  // OK, three numbers
Real-world example
Typing a function's arguments where the first argument has a fixed meaning (like a format string) followed by a variable number of typed values.
Likely follow-ups
  • Can a rest element appear at the START of a tuple instead of the end?
Related topics