Tuples: Fixed-Length, Typed Lists
A tuple is an array with a fixed length where each position has its own type.
What you will learn
- Define a tuple with typed positions
- See how tuples differ from normal arrays
- Use a realistic tuple example
An array where order and types are fixed
A normal array holds many values of one type. A tuple is special: it has a fixed number of items, and each position has its own type. The order matters.
// [name, age] — position 0 is a string, position 1 is a number
let person: [string, number] = ['Asha', 21];
console.log(person[0].toUpperCase()); // string method, ok
console.log(person[1] + 1); // number maths, okNote: Output:
ASHA
22
TypeScript knows position 0 is a string and position 1 is a number, so it allows .toUpperCase() on the first and + 1 on the second.
Tuples catch wrong order and length
let person: [string, number];
person = ['Asha', 21]; // correct
person = [21, 'Asha']; // error — types are in the wrong order
person = ['Asha']; // error — wrong lengthNote: Output: Error: Type 'number' is not assignable to type 'string' (position 0). Error: Source has 1 element(s) but target requires 2. A tuple is strict: each slot must match its declared type, and the length must be exactly right.
A realistic use: a coordinate
Tuples shine for small fixed groups, like an (x, y) point or an RGB colour (RGB = the Red, Green and Blue amounts that make up a colour, e.g. [255, 0, 0] for red):
type Point = [number, number];
function distanceFromOrigin(p: Point): number {
return Math.sqrt(p[0] * p[0] + p[1] * p[1]);
}
console.log(distanceFromOrigin([3, 4]));Note: Output:
5
The Point tuple guarantees exactly two numbers, so the maths is safe. (3, 4) is 5 units from the origin.
Tip: You meet tuples in real code: React's useState returns a tuple [value, setValue]. Knowing tuples helps you understand why const [count, setCount] = useState(0) works.
Watch out: Tuples are easy to misuse for big groups. If positions start meaning different things and the list grows, an object/interface with named properties is clearer than [string, number, boolean, number].
Q. How is a tuple different from a normal array?
✍️ Practice
- Declare a tuple
[string, boolean]for a setting like ["darkMode", true]. - Write a
type RGB = [number, number, number]and create a colour value.
🏠 Homework
- Write a function that takes a
[string, number]tuple of (product, price) and returns a formatted label, with its output.