Arrays and Tuples
Learn how to take full control of lists in TypeScript using typed arrays and tuples that are structured, safe, and deeply expressive.
We'll cover the following...
- Typed arrays: Predictability with every element
- Arrays in functions: Input, output, and locked contracts
- Tuples: Fixed-length structure with built-in intent
- Tuples in functions: Lightweight structure without objects
- Labelled tuples: Clarity without overhead
- Choosing between arrays and tuples
- Exercise: Write a leaderboard ranking function
JavaScript arrays are flexible—sometimes too flexible. We can mix types. Push in anything. Return all kinds of shapes. And JavaScript won’t say a word until something breaks at runtime.
TypeScript helps enforce expectations at compile time; it doesn’t change JavaScript runtime behavior. It gives us tools to say, “This array holds only strings” or “This collection will always have exactly two items: first a name, then a score.” We make our expectations clear, and the compiler enforces them with zero compromise.
They make our code more readable and help catch mistakes earlier.
Let’s dig in.
Typed arrays: Predictability with every element
Here’s a basic example. Imagine we’re tracking blog tags, user IDs, and boolean flags. This is what it might look like in plain JavaScript: