Skip to content

Arrays and Tuples

A typed array (number[] or Array<number>) holds an arbitrary number of items, all of the same type. A tuple ([string, number]) is a fixed-length array where each position has its own, potentially different, type β€” useful for representing something like a coordinate pair or a [key, value] entry.

const scores: number[] = [10, 20, 30];
scores.push(40); // fine -- number
// scores.push("40"); // Error: string not assignable to number
const names: Array<string> = ["Alice", "Bob"]; // equivalent syntax
const point: [number, number] = [3, 4];
const [x, y] = point; // destructuring -- x: number, y: number
const entry: [string, number] = ["age", 30];
// const bad: [string, number] = [30, "age"]; // Error: wrong order/types
function useState<T>(initial: T): [T, (value: T) => void] {
let value = initial;
return [value, (v: T) => { value = v; }];
}

Treating a tuple like a regular array and pushing extra items onto it β€” TypeScript’s tuple type checks the declared positions strictly, but .push() isn’t blocked by default, silently letting the tuple grow beyond its intended shape.

const point: [number, number] = [3, 4];
point.push(5); // no compile error! now [3, 4, 5] at runtime
console.log(point); // [3, 4, 5] -- no longer really a "point"
// If you need a fixed-length, immutable tuple, mark it readonly
const safePoint: readonly [number, number] = [3, 4];
// safePoint.push(5); // Error: Property 'push' does not exist on type 'readonly [number, number]'
  1. What’s the main difference between an array type and a tuple type in TypeScript?

    AnswerAn array holds any number of items of the same type; a tuple has a fixed length where each position can have its own distinct type.
  2. Does .push() respect a tuple’s fixed length by default?

    AnswerNo β€” TypeScript's tuple type checking doesn't block .push() by default, so a tuple can grow beyond its declared length at runtime unless marked readonly.
  3. How do you write the type for a fixed pair of [string, number] that shouldn’t be mutated?

    Answerreadonly [string, number]