readonly Arrays and Tuples
Lock arrays and tuples against mutation methods.
Readonly Arrays
A readonly array is an array you can read from but not modify. Write it as readonly number[] or equivalently ReadonlyArray<number>. The element type stays the same; only mutation is blocked.
const nums: readonly number[] = [1, 2, 3];
console.log(nums[0], nums.length);
// nums[0] = 9; // Error: index signature is readonlyThe ReadonlyArray Type
ReadonlyArray<T> is the generic form, identical in meaning to readonly T[]. Use whichever reads better; they're interchangeable.
const names: ReadonlyArray<string> = ['Ada', 'Sam'];
console.log(names.join(', '));All lessons in this course
- readonly Properties
- readonly Arrays and Tuples
- ReadonlyArray and ReadonlyMap
- Deep Immutability Patterns