typescript-tuplas

Using Tuples in TypeScript

  • 4 min

In TypeScript, a tuple is a special type of array that allows storing a fixed number of elements with specific types in each position.

Tuples are useful when we know exactly how many and what types of elements we want to store in a grouping.

If you want to learn more, check out the Introduction to Programming Course

To declare a tuple, a syntax similar to arrays is used, but specifying the types of each element within brackets.

let tuple: [number, string, boolean];
tuple = [1, "TypeScript", true];
Copied!

In this example, the tuple tuple can contain a number, a string, and a boolean value, in that specific order.

Tuple Initialization

Tuples must be initialized with the exact number and type of elements specified in their declaration.

// Correct
let correctTuple: [number, string] = [42, "Hello"];

// Incorrect
let incorrectTuple: [number, string] = [42];  // Error: Missing elements
let incorrectTupleTypes: [number, string] = [42, true];  // Error: Incorrect types
Copied!

Attempting to assign a different number of elements (more or less) or elements of incorrect types will cause a compilation error

Accessing and Manipulating Tuples

Accessing Elements

Elements of a tuple can be accessed using the index (same as in an array).

let myTuple: [string, number, boolean] = ["TypeScript", 2024, true];

console.log(myTuple[0]);  // "TypeScript"
console.log(myTuple[1]);  // 2024
console.log(myTuple[2]);  // true
Copied!

Assigning Values

You can reassign the values of tuple elements using their index, but they must maintain the original type.

myTuple[1] = 2025;  // Correct
myTuple[2] = false;  // Correct

// Incorrect
// myTuple[1] = "2025";  // Error: Incorrect type
Copied!

Tuple Destructuring

TypeScript supports tuple destructuring, which allows assigning the values of a tuple to individual variables conveniently.

let [language, year, active] = myTuple;
console.log(language);  // "TypeScript"
console.log(year);      // 2024
console.log(active);    // true
Copied!

Common Array Methods in Tuples

Tuples inherit several array methods, although their use may be limited due to the fixed nature of tuples.

push()

Adds an element to the end of the tuple. However, this can break the tuple if elements of unexpected types are added.

myTuple.push("new element");  // Now it's [string, number, boolean, string]
Copied!

pop()

Removes the last element from the tuple.

let lastElement = myTuple.pop();  // "new element"
Copied!

concat()

Combines two or more tuples (or arrays).

let myTuple: [string, number, boolean] = ["TypeScript", 2024, true];
let anotherTuple: [string, number] = ["Hello", 100];
let combined = myTuple.concat(anotherTuple);

console.log(combined);  // ["TypeScript", 2024, false, "Hello", 100]
Copied!

Advanced Tuple Types

Practical Examples