Arrays and Tuples
Explore how TypeScript uses typed arrays and tuples to enforce strict data structures and improve code quality. Understand when to use arrays for uniform data and tuples for fixed, ordered types. Gain the ability to write functions that leverage these structures with full type safety, making your code more predictable and maintainable.
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.
This is where TypeScript steps in—not to slow us down, but to lock things in. 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.
Typed arrays and tuples don’t just catch bugs—they communicate intent. They make our code more readable and more testable.
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:
The problem? These arrays have no enforced type. We could easily push the wrong kind of value and JavaScript would let it slide.
TypeScript changes that. TypeScript doesn’t just ask us to write arrays differently. It asks us to think about arrays differently. A typed array is a contract. It tells TypeScript and every teammate reading our code—exactly what belongs in that list. It draws a clear boundary and says: “Only these types are allowed. Everything else? Don’t even try.”
There are two ways to write a typed array:
Explanation:
-
Line 1: We define tags as a
string[], which means every element must be a string. -
Line 2:
Array<number>does the same for numbers—it’s just a different syntax, useful in ...