Arrays & Tuples
Typed arrays, readonly, and fixed-length tuples
Skills taught: ts.typed-arrays, ts.tuples, ts.readonly, ts.array-methods
Typed arrays
// Array of numbers — two equivalent syntaxes
const scores: number[] = [95, 87, 72, 100];
const names: Array<string> = ['Alice', 'Bob', 'Charlie'];
// TypeScript knows the element type, so methods are typed
const doubled = scores.map(n => n * 2); // number[]
const upper = names.map(s => s.toUpperCase()); // string[]
// Cannot push wrong type
scores.push(88); // OK
// scores.push('great'); // Error: string is not assignable to number
// Readonly array — cannot mutate
const fixed: readonly number[] = [1, 2, 3];
// fixed.push(4); // Error: push does not exist on readonly number[]
// fixed[0] = 99; // Error: Index signature is readonly
// Multi-dimensional
const matrix: number[][] = [[1, 0], [0, 1]];
// Type is inferred from content
const inferred = [1, 2, 3]; // number[]
const mixed = [1, 'two', true]; // (number | string | boolean)[]
Tuples
// Tuple: fixed length, each position has its own type
const point: [number, number] = [10, 20]; // x, y
const entry: [string, number] = ['Alice', 95]; // name, score
// Named tuple elements (TS 4.0) — better IDE support
type Coordinate = [x: number, y: number];
const loc: Coordinate = [48.8, 2.3];
console.log('x:', loc[0], 'y:', loc[1]);
// Destructuring tuples
const [name, score] = entry;
console.log(`${name} scored ${score}`);
// Optional tuple elements
type RGB = [r: number, g: number, b: number, a?: number];
const red: RGB = [255, 0, 0]; // no alpha
const transparent: RGB = [0, 0, 0, 0]; // with alpha
// as const — infers literal tuple type
const STATUS = ['active', 'inactive', 'pending'] as const;
// type: readonly ['active', 'inactive', 'pending']
type Status = typeof STATUS[number]; // 'active' | 'inactive' | 'pending'
// Useful pattern: function returning multiple values as tuple
function divmod(a: number, b: number): [quotient: number, remainder: number] {
return [Math.floor(a / b), a % b];
}
const [q, r] = divmod(17, 5);
console.log(`17 / 5 = ${q} remainder ${r}`);
Frequently Asked Questions
When should I use a tuple vs an object?
Tuples work well for 2-3 element structures where order is the convention (coordinates [x, y], divmod result [quotient, remainder]). Beyond 3 elements, or when the structure has named fields, use an interface or object: { x: number, y: number } is clearer than [number, number] when there are many fields.