Fixed-Length Arrays vs Tuples
What you'll learn: You'll understand the difference between arrays with unknown lengths and tuples with exact, fixed lengths.
The Core Difference
When you declare an array like const items: string[] = ["a", "b", "c"], TypeScript knows it contains strings, but it doesn't know how many. The array could have 3 elements, 30 elements, or grow to any length during runtime. TypeScript treats items[0] as string | undefined because it can't guarantee that index exists.
A tuple, on the other hand, is a fixed-length array where TypeScript knows exactly how many elements there are and what type each position holds. It's like a contract: "This will always have exactly 2 items—a string followed by a number."
When to Use Each
Use regular arrays when:
- The collection's size can change (adding/removing items)
- You're working with homogeneous data (all same type)
- Length doesn't matter for your logic
Use tuples when:
- You have a fixed structure (like coordinates:
[x, y]) - Each position has a specific meaning
- You're returning multiple values from a function
- Length is part of your data's contract
Analogy
Think of a regular array like a shopping list—you can keep adding items, and there's no fixed number. A tuple is like a form with specific fields: "Name (text) and Age (number)"—exactly two slots, each with its own purpose.
Key Takeaway: Regular arrays have flexible, unknown lengths and TypeScript can't guarantee specific indices exist, while tuples define exact lengths and types for each position, giving you stronger type safety when structure matters.