ReadonlyArray and ReadonlyMap
Use built-in readonly collection types.
ReadonlyArray and ReadonlyMap is a free TypeScript Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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'); // ErrorReadonlyMap
ReadonlyMap<K, V> lets you look up, iterate, and check keys, but removes set, delete, and clear. The map's contents are fixed from the consumer's perspective.
const ages: ReadonlyMap<string, number> = new Map([['Ada', 30], ['Sam', 25]]);
console.log(ages.get('Ada'), ages.has('Sam'));
// ages.set('Lee', 40); // ErrorReading From a ReadonlyMap
All the read operations remain: get, has, size, keys, values, entries, and iteration. Only the mutating methods are gone.
const m: ReadonlyMap<string, number> = new Map([['a', 1], ['b', 2]]);
for (const [k, v] of m) {
console.log(k, v);
}
console.log('size:', m.size);ReadonlySet
ReadonlySet<T> supports membership checks and iteration but removes add, delete, and clear. Use it for fixed sets of allowed values.
const allowed: ReadonlySet<string> = new Set(['read', 'write']);
console.log(allowed.has('read'), allowed.has('delete'));
// allowed.add('admin'); // ErrorIterating a ReadonlySet
You can iterate a ReadonlySet and read its size, just not change its contents. This makes it ideal for whitelists and permission sets.
const perms: ReadonlySet<string> = new Set(['view', 'edit']);
perms.forEach((p) => console.log('perm:', p));
console.log('count:', perms.size);Passing Readonly to Functions
Accept a readonly collection type in functions that should only read. It communicates intent and prevents the function from mutating data owned by the caller.
function describe(set: ReadonlySet<string>): string {
return 'has ' + set.size + ' items';
}
const s = new Set(['x', 'y']);
console.log(describe(s));Mutable Collections Are Assignable
A regular Map or Set is assignable to its readonly counterpart, because you're narrowing capabilities, not widening them. The function simply gives up mutation rights.
function keys(m: ReadonlyMap<string, number>): string[] {
return Array.from(m.keys());
}
const real = new Map([['a', 1]]);
console.log(keys(real));Immutable Collection APIs
Readonly collection types describe an immutable view. The underlying object may still be mutable elsewhere; the readonly type only restricts what this reference can do.
const backing = new Set<number>([1, 2]);
const view: ReadonlySet<number> = backing;
// view.add(3); // Error through the readonly view
backing.add(3); // but the original can still mutate
console.log(view.size);Choosing the Right Readonly Type
Match the readonly type to your data structure: ReadonlyArray for ordered lists, ReadonlyMap for key-value lookups, ReadonlySet for unique membership. Each enforces immutability for its shape.
const roles: ReadonlySet<string> = new Set(['admin', 'user']);
const limits: ReadonlyMap<string, number> = new Map([['admin', 100]]);
console.log(roles.has('user'), limits.get('admin'));Safer Shared State
Exposing internal collections as readonly types prevents callers from corrupting your module's state. They can inspect the data freely, but only your code can change it.
class Registry {
private items = new Set<string>();
add(name: string): void { this.items.add(name); }
get all(): ReadonlySet<string> { return this.items; }
}
const r = new Registry();
r.add('a');
console.log(r.all.has('a'));Quick Check
Test your understanding of readonly collection types.
Recap: Readonly Collections
You learned the readonly collection family:
ReadonlyArray<T>,ReadonlyMap<K, V>,ReadonlySet<T>expose only read operations.- Mutating methods (
set,add,delete,push) are removed. - Mutable collections are assignable to their readonly counterparts.
- They make great parameter and return types for safer shared state.
Finally, deep immutability patterns.
function count(s: ReadonlySet<number>): number {
return s.size;
}
console.log(count(new Set([1, 2, 3])));Frequently asked questions
Is the “ReadonlyArray and ReadonlyMap” lesson free?
Yes — the full text of “ReadonlyArray and ReadonlyMap” is free to read here on the web, and the TypeScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.
What will I learn in “ReadonlyArray and ReadonlyMap”?
Use built-in readonly collection types. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start TypeScript Academy?
No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “ReadonlyArray and ReadonlyMap” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this TypeScript Academy lesson?
Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- readonly Properties
- readonly Arrays and Tuples
- ReadonlyArray and ReadonlyMap
- Deep Immutability Patterns