Typing Arrays and Tuples
Typed arrays, readonly arrays, and fixed-length tuples with position-specific types.
2 min read
Arrays got a brief mention early in this course; this lesson covers them more fully, plus tuples — arrays with a fixed length and a specific type at each position.
Typed arrays
let scores: number[] = [10, 20, 30];
let names: string[] = ["Ada", "Grace"];Every element must match the declared type — pushing a mismatched value is a compile error, and so is reading an element and using it as the wrong type elsewhere.
Arrays of union types
let mixed: (string | number)[] = ["a", 1, "b", 2];Parentheses matter here: (string | number)[] means "an array where each element is a string or a number." Without them, string | number[] means something different — "either a string, or an array of numbers" — since [] would bind to number alone.
Arrays of objects
interface User {
name: string;
age: number;
}
let users: User[] = [
{ name: "Ada", age: 36 },
{ name: "Grace", age: 45 },
];This is one of the most common shapes in real code — typed arrays combined with array methods from JavaScript retain full type safety through the chain:
const names: string[] = users.map(user => user.name); // fully typed, no `any`Tuples: fixed length, position-specific types
A tuple looks like an array type but fixes both the length and the type at each position:
let point: [number, number] = [10, 20];
let entry: [string, number] = ["age", 36];
point = [10, 20, 30]; // Source has 3 element(s) but target allows only 2
entry = [36, "age"]; // wrong order -- type mismatch at each positionRegular arrays don't enforce length or per-position types; tuples do. They're useful for a small, fixed structure where each position has a specific meaning — a coordinate pair, or a [key, value] entry (which is exactly what Object.entries() returns, and TypeScript types it as an array of tuples).
Named tuple elements
type Coordinate = [x: number, y: number];
function move(point: Coordinate) {
console.log(`Moving to ${point[0]}, ${point[1]}`);
}The names (x, y) exist purely for readability in editor tooltips and don't change the runtime behavior — point is still a plain two-element array at runtime, same as any tuple.
readonly tuples and arrays
function processPoint(point: readonly [number, number]) {
point[0] = 99; // Cannot assign to '0' because it is a read-only property
}Same principle as readonly on object properties, covered earlier — it's a compile-time guarantee that a function won't mutate the array or tuple it was given.
The next lesson moves to classes — where TypeScript's types combine with object-oriented features like access modifiers and constructor shortcuts.