Sub topic 2
Readonly Arrays and Tuples
Assume you know JavaScript arrays, basic TypeScript annotations, and union types. This chapter focuses on preserving guarantees when data is passed between functions.
Readonly arrays
A readonly array lets a function read elements without changing the array through that reference. Both readonly T[] and ReadonlyArray<T> express this type.
function total(values: readonly number[]): number {
return values.reduce((sum, value) => sum + value, 0);
}
const scores: readonly number[] = [90, 85, 72];
console.log(total(scores));
// scores.push(100); // Error: push does not exist on a readonly arrayreadonly protects the reference used by total. It does not make every object inside the array immutable. Also, another mutable reference could still change the same underlying array.
Tuples: fixed length, typed positions
A tuple is an array type with a known length and a specific type at each position.
type Point = [number, number];
const point: Point = [10, 20];
const [x, y] = point;
console.log(x + y); // 30The first element is a number, and the second element is also a number. A tuple can represent a fixed record whose values are naturally grouped together.
A readonly tuple prevents mutation:
const origin: readonly [number, number] = [0, 0];
// origin.push(1); // ErrorWhen to use a tuple and when to use an array
Use an array when all elements have the same role and the length can vary, such as a list of scores. Use a tuple when position gives an element meaning, such as [latitude, longitude] or [minimum, maximum].
Destructuring and returning multiple values
Functions can return tuples so callers receive multiple typed values without losing their positions.
function minMax(values: readonly number[]): [number, number] {
if (values.length === 0) {
throw new Error("values must not be empty");
}
return [Math.min(...values), Math.max(...values)];
}
const [minimum, maximum] = minMax([3, 1, 4, 1, 5]);
console.log(minimum, maximum); // 1 5The return annotation guarantees exactly two numbers. Destructuring assigns them to meaningful local names.
Exercise
Should a function accepting a list of numbers use number[] or readonly number[] if it only calculates a result?
Show answer
Use readonly number[] because the function does not need to mutate its input.