Tuple Type
A tuple is a sub-type of an array. It is similar to an array in that it can hold elements of different data types, but it differs in that it has a finite number of elements.
Example:
1 |
|
Variadic Tuple Types
Variadic tuple types are a feature in TypeScript that allow an indefinite number of elements. The syntax for defining a variadic tuple type is to use the rest syntax (...
) to condense multiple elements into one:
1 |
|
In the code example above, a benefit of using a variadic tuple type over an array (Array<string | number>
) is that it enforces that the first element of the tuple must be of type string
.
Labeled Tuple Elements
As of TypeScript 4.0 you can assign labels to the elements of a tuple type for improved readability:
1 |
|
Tuples vs. Arrays
A tuple has a fixed number of elements and arrays have a variable number of elements.
Example:
1 |
|
Tuple types are denoted by square brackets placed outside of the data type (e.g. [number]
), while array types have square brackets following the data type (e.g. number[]
):
1 |
|