What is Tuple

In TypeScript, a tuple is a typed array with a fixed number of elements whose types are known and can be different. Tuples allow you to express an array where the type of a fixed number of elements is known but need not be the same.

Defining Tuples

You define a tuple by specifying the types of its elements inside square brackets.


let tuple: [string, number];
tuple = ["Hello", 42]; // OK
// tuple = [42, "Hello"]; // Error: Type 'number' is not assignable to type 'string' and vice versa

Accessing Tuple Elements

You can access the elements of a tuple using array indexing.

let tuple: [string, number];
tuple = ["Hello", 42];

console.log(tuple[0]); // Outputs: Hello
console.log(tuple[1]); // Outputs: 42

Tuple Operations

Pushing to Tuples

You can push new elements to a tuple, but it may lose the tuple type and become a regular array type.

let tuple: [string, number];
tuple = ["Hello", 42];

console.log(tuple); // Outputs: ["Hello", 42, "World"]

Destructuring Tuples

You can destructure tuples just like arrays.

let tuple: [string, number];
tuple = ["Hello", 42];

let [greeting, answer] = tuple;

console.log(greeting); // Outputs: Hello
console.log(answer);   // Outputs: 42

Tuple Types with Optional Elements

Tuples can also have optional elements.

let tuple: [string, number?];
tuple = ["Hello"];
tuple = ["Hello", 42];

console.log(tuple); // Outputs: ["Hello"] or ["Hello", 42]

Tuple Rest Elements

TypeScript 3.0 introduced support for rest elements in tuple types, which can represent a variable number of elements.

let tuple: [string, ...number[]];
tuple = ["Hello"];
tuple = ["Hello", 40, 41, 42];

console.log(tuple); // Outputs: ["Hello", 40, 41, 42]