Tuples vs Arrays
What you'll learn: How to decide when to use a tuple and when to use an array in TypeScript.
When to Choose Each
You've learned about both arrays and tuples, but when should you actually use each one? The key difference comes down to structure vs collection.
Arrays are for homogeneous collections where:
- All elements are the same type
- The length can grow or shrink
- Order matters but position doesn't have special meaning
Think of an array like a shopping list — you can add items, remove items, and each item is the same kind of thing (groceries).
Tuples are for heterogeneous, structured data where:
- Each position has a specific meaning
- The length is fixed (or has a known structure)
- Each element might be a different type
Think of a tuple like coordinates — [latitude, longitude] — where the first number always means latitude and the second always means longitude.
Practical Examples
Use an array for:
const scores: number[] = [95, 87, 92]; // Can add more scores
const usernames: string[] = ["alice", "bob"]; // Can add more users
Use a tuple for:
const coordinate: [number, number] = [40.7128, -74.0060]; // Always lat, lng
const response: [number, string] = [200, "OK"]; // Status code, message
The tuple enforces that you can't accidentally swap the status code and message, or add a third element where it doesn't belong.
Key Takeaway: Use arrays for flexible collections of similar items; use tuples when each position has a specific, meaningful role in a fixed structure.