Arrays and Tuples
Arrays and Tuples
Section titled βArrays and TuplesβWhat it means
Section titled βWhat it meansβ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.
Examples
Section titled βExamplesβ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; }];}Common mistake
Section titled βCommon mistakeβ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 runtimeconsole.log(point); // [3, 4, 5] -- no longer really a "point"
// If you need a fixed-length, immutable tuple, mark it readonlyconst safePoint: readonly [number, number] = [3, 4];// safePoint.push(5); // Error: Property 'push' does not exist on type 'readonly [number, number]'Quick practice
Section titled βQuick practiceβ-
Whatβs the main difference between an array type and a tuple type in TypeScript?
Answer
An 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. -
Does
.push()respect a tupleβs fixed length by default?Answer
No β TypeScript's tuple type checking doesn't block.push()by default, so a tuple can grow beyond its declared length at runtime unless markedreadonly. -
How do you write the type for a fixed pair of
[string, number]that shouldnβt be mutated?Answer
readonly [string, number]