BeCuriouzBeCuriouz

Learn something new every day

🔷 TypeScript
📦

Arrays and Tuples: When Position Has Meaning

💡 Use T[] for a variable-length list of one type, and a tuple like [string, number] when each position has a fixed type and meaning.

Recall how we annotate a variable with a type like string or number. To describe a list of values that all share one type, add [] after the type. So number[] is "an array of numbers" and string[] is "an array of strings." TypeScript then checks every element for you.

ts
const scores: number[] = [90, 85, 100];
scores.push(72);      // ✅ a number
scores.push("A+");    // ❌ Error: string is not a number

An array can hold any number of elements, and each position is interchangeable. But sometimes position carries meaning — the first slot is always a name, the second always an age. For that, use a tuple: a fixed-length array where each position has its own type.

ts
let person: [string, number] = ["Ada", 36];
person[0].toUpperCase();  // ✅ string method
person[1].toFixed(2);     // ✅ number method
let bad: [string, number] = [36, "Ada"];  // ❌ order is wrong

The key difference: a T[] says "many of the same thing, length unknown," while a tuple says "exactly these types, in exactly this order." Reach for arrays when you have a collection; reach for tuples when each slot plays a distinct role, like a coordinate [number, number] or a labeled pair.

📦 Arrays and Tuples: When Position Has Meaning — BeCuriouz