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
2
type MyTupleType = [string, number];
const benny: MyTupleType = ['Benny', 34];

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
2
3
type MyVariadicTupleType = [string, ...number[]];

const array: MyVariadicTupleType = ['prime numbers', 2, 3, 5, 7, 11];

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
2
type MyTupleType = [name: string, age: number];
const benny: MyTupleType = ['Benny', 34];

Tuples vs. Arrays

A tuple has a fixed number of elements and arrays have a variable number of elements.

Example:

1
2
3
4
5
6
7
// Tuple, fixed size of elements
const id: [number] = [15];

// Array
const ids: number[] = [1, 2, 3];
// More and more elements can be pushed
ids.push(4);

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
2
const tuple: [string, number] = ['Benny', 34];
const array: (string | number)[] = ['Benny', 34];