Language: EN

typescript-tuplas

Using Tuples in TypeScript

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.

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

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

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

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

The elements of a tuple can be accessed using the index (just like 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

Assigning Values

The values of the elements of a tuple can be reassigned 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

Destructuring Tuples

TypeScript supports tuple destructuring, allowing the values of a tuple to be assigned to individual variables conveniently.

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

Common Array Methods on 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]
  • pop(): Removes the last element from the tuple.
let lastElement = myTuple.pop();  // "new element"
  • 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, true, "Hello", 100]

Advanced Tuple Types

Tuples with Optional Elements

TypeScript allows defining tuples with optional elements using the symbol ?.

let optionalTuple: [number, string?, boolean?];
optionalTuple = [1];
optionalTuple = [1, "Optional"];
optionalTuple = [1, "Optional", true];

Tuples with Rest Elements

Tuples can also use rest elements (...) to allow a variable number of elements of a specific type at the end of the tuple.

let restTuple: [number, ...string[]];
restTuple = [1];
restTuple = [1, "a", "b", "c"];

Tuples as Function Parameters

Tuples can be very useful as function parameters to ensure that a specific set of types is received in a particular order.

function processTuple(tuple: [string, number, boolean]): void {
    let [text, number, booleanValue] = tuple;
    console.log(`Text: ${text}, Number: ${number}, Boolean: ${booleanValue}`);
}

processTuple(["TypeScript", 2024, true]);

Practical Examples

Using Tuples to Represent Key-Value Pairs

let keyValuePair: [string, any][] = [
    ["name", "Juan"],
    ["age", 30],
    ["active", true]
];

keyValuePair.forEach(([key, value]) => {
    console.log(`${key}: ${value}`);
});
// name: Juan
// age: 30
// active: true

Returning Multiple Values from a Function

function calculate(a: number, b: number): [number, number, number, number] {
    return [a + b, a - b, a * b, a / b];
}

let [sum, difference, multiplication, division] = calculate(10, 2);
console.log(`Sum: ${sum}, Difference: ${difference}, Multiplication: ${multiplication}, Division: ${division}`);
// Sum: 12, Difference: 8, Multiplication: 20, Division: 5