TS Tuples

TypeScript Tuples

A tuple is a very specific type of array with a fixed, predetermined length.

Furthermore, the type of each element at each specific position is known.

This is incredibly useful when you want to group different types together safely.

Tuples are heavily used in React hooks, like useState, under the hood.


1. Defining a Tuple

To define a tuple, you use square brackets containing a list of types.

The order of the values must perfectly match the order of the types you declared.

If the order is wrong, TypeScript will immediately throw a compilation error.

Basic Tuple Example:

// Define a tuple with a string and a number
let ourTuple: [string, number];

// Initialize it correctly ourTuple = ["Age", 25];

console.log("Tuple initialized:", ourTuple);


2. Order Matters Heavily

Because the positions are strictly typed, you cannot flip the values around.

This prevents critical data mismatches when passing arguments between functions.

It is one of the most powerful features for strict data integrity in applications.

Incorrect Order Example:

let wrongTuple: [number, string];

// wrongTuple = ["Error", 404]; // This causes an error! // It expects a number first, then a string.

wrongTuple = [404, "Not Found"]; // Correct

console.log("Status:", wrongTuple[0], wrongTuple[1]);


3. Readonly Tuples

By default, you can technically push new items into a tuple, which defeats its purpose.

To prevent this, it is a best practice to make your tuples readonly.

This guarantees the structure will never change during runtime execution.

Readonly Tuple Example:

let safeTuple: readonly [number, boolean] = [1, true];

// safeTuple.push(false); // Error! Cannot push to readonly tuple.

console.log(safeTuple[0]); // Outputs 1


Exercise

?

What makes a tuple different from a regular array?


4. Final Thoughts

Tuples are excellent for returning multiple related values from a function.

They provide structural safety that standard arrays simply cannot offer.

Next, we will look at typing more complex Object structures!