Tuples

Learn tuples in TypeScript, including named element types, tuple destructuring, optional elements, and spread syntax for variable-sized tuples.

Introduction to tuples in TypeScript

Tuples are a method of defining a type that has a finite number of unnamed properties, with each property having an associated type. When using a tuple, all of the properties must be provided.

This can best be explained in an example as follows:

// Declare a tuple called tuple1 with elements of type string and boolean
let tuple1: [string, boolean];
// Assign values "test" and true to the tuple
tuple1 = ["test", true];
// This assignment is incorrect as it is missing a second element of type boolean
// and will result in a TypeScript error
tuple1 = ["test"];
Incorrect tuple assignment
  • We define a variable named tuple1 on line 2, whose type is defined as an array of types. The first type is a string, and the second type is a boolean.

  • We then assign a value to the tuple1 variable on line 5 that contains an array with two values: the first of type string and the second of type boolean.

Note that line 9 of this code generates an error because it attempts to assign a value to the tuple1 variable that does not have all of the properties that are required.

What this error is telling us is that the number and types defined in a tuple must be provided when we assign anything to a tuple.

Tuple destructuring

As tuples use the array syntax, they can be destructured or disassembled in two ways.

The first way of destructuring a ...