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.
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:
const tags = ['typescript', 'javascript', 'backend'];const ids = [101, 102, 103];const flags = [true, false, true];// JavaScript will happily lets us do this:tags.push(42); // Uh-oh… a number in a string array?ids.push('hello'); // And now a string in a number array?flags.push('maybe'); // This one really shouldn't be allowedconsole.log(`Tags: ${tags}, IDs: ${ids}, Flags: ${flags}`);
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:
const tags: string[] = ['typescript', 'javascript', 'backend'];const ids: Array<number> = [101, 102, 103];tags.push('node'); // ✅ OKtags.push(42); // ❌ Error!console.log(`Tags: ${tags}, IDs: ${ids}`);
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 ...