ReadonlyArray and ReadonlyMap
Use built-in readonly collection types.
Readonly Collection Types
Beyond arrays, TypeScript ships readonly variants of its built-in collections: ReadonlyArray<T>, ReadonlyMap<K, V>, and ReadonlySet<T>. Each exposes only the non-mutating parts of its API.
const arr: ReadonlyArray<number> = [1, 2, 3];
console.log(arr.length, arr.includes(2));ReadonlyArray Recap
ReadonlyArray<T> allows iteration, indexing, and methods like map and filter, but not push, pop, or index assignment. It's the array form of the readonly family.
const tags: ReadonlyArray<string> = ['ts', 'js'];
console.log(tags.map((t) => t.toUpperCase()));
// tags.push('css'); // ErrorAll lessons in this course
- readonly Properties
- readonly Arrays and Tuples
- ReadonlyArray and ReadonlyMap
- Deep Immutability Patterns