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 booleanlet tuple1: [string, boolean];// Assign values "test" and true to the tupletuple1 = ["test", true];// This assignment is incorrect as it is missing a second element of type boolean// and will result in a TypeScript errortuple1 = ["test"];
-
We define a variable named
tuple1
on line 2, whose type is defined as an array of types. The first type is astring
, and the second type is aboolean
. -
We then assign a value to the
tuple1
variable on line 5 that contains an array with two values: the first of typestring
and the second of typeboolean
.
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 ...