Readonly Arrays and Immutable Data
Use ReadonlyArray to prevent accidental mutations.
Welcome
Mutable arrays can be accidentally modified anywhere in your code. TypeScript's ReadonlyArray and readonly modifier help you enforce immutability.
The readonly Modifier on Arrays
Add the `readonly` modifier before the array type to prevent mutation. The array can be read but not changed.
const ids: readonly number[] = [1, 2, 3];
// ids.push(4); // Error
// ids[0] = 99; // Error
console.log(ids[0]); // OK — reading is fineAll lessons in this course
- Typed Arrays: T[] and Array
- Readonly Arrays and Immutable Data
- Tuples: Fixed-Length Typed Arrays
- Enums: Numeric and String Constants