Sub topic 8
Readonly dictionaries
This chapter assumes you can declare a string index signature, you know that noUncheckedIndexedAccess makes lookups return T | undefined, and you are comfortable with readonly on interface properties. It covers how to mark a dictionary as read-only, what that guarantee does and does not cover, and which tool to pick when you need a stronger one.
Why make a dictionary read-only
Many dictionaries are built once and then only read. Examples are a table of default settings, a lookup of error messages, and a set of limits loaded at startup. If any function can write to them, a typo or a careless helper can change shared state, and the bug shows up far from the cause.
TypeScript lets you state the intent in the type. The compiler then rejects every write that goes through that type. This is the same idea as readonly on a property or ReadonlyArray<T>, applied to every key an index signature covers.
The readonly index signature
Put readonly in front of the index signature:
interface ReadonlyDict {
readonly [key: string]: number;
}
const limits: ReadonlyDict = { max: 10 };
console.log(limits["max"]); // 10
// limits["max"] = 20; // Error: Index signature in type 'ReadonlyDict' only permits reading.
// limits.min = 1; // Error: Index signature in type 'ReadonlyDict' only permits reading.Reads work as usual. Writes are rejected whether you use bracket or dot notation, and whether the key already exists or not. You cannot add new keys either, because adding a key is also a write through the index signature.
The object literal on the right-hand side is still checked normally. Every value in it must be a number, and the initializer is the only place where you write the data.
Readonly\<Record\> and inline types
You do not have to declare an interface. Two other spellings give the same result.
function total(values: Readonly<Record<string, number>>): number {
return Object.values(values).reduce((sum, n) => sum + n, 0);
}
function describe(values: { readonly [key: string]: number }): string {
return Object.keys(values).join(", ");
}
console.log(total({ a: 1, b: 2 })); // 3
console.log(describe({ a: 1, b: 2 })); // "a, b"Readonly<T> is a mapped type that adds readonly to every property. Applied to Record<string, number>, it produces { readonly [x: string]: number }, which is the same type as the interface above.
Using a read-only type for function parameters is a good habit. The signature tells callers that the function will not modify their dictionary, and it stops you from accidentally doing so inside the function.
What the compiler enforces
The table summarizes how readonly on an index signature behaves.
| Operation | Allowed on a readonly index signature? |
|---|---|
| Read with `d["k"]` or `d.k` | Yes |
| Assign with `d["k"] = v` | No |
| Iterate with `Object.keys`, `Object.values`, `Object.entries` | Yes |
| Create a new object with spread, `{ ...d, k: v }` | Yes |
| Call a mutating method on a value stored in it, such as `push` | Depends on the value type |
The last row matters because readonly is shallow. It protects the slots of the dictionary and says nothing about the values in them.
Updating without mutating
When a read-only dictionary has to change, you build a new one. Spread copies the entries and a computed key overrides one of them:
interface ReadonlyDict {
readonly [key: string]: number;
}
function withLimit(base: ReadonlyDict, key: string, value: number): ReadonlyDict {
return { ...base, [key]: value };
}
const original: ReadonlyDict = { max: 10 };
const updated = withLimit(original, "max", 20);
console.log(original["max"]); // 10
console.log(updated["max"]); // 20This is the usual pattern for state that must not be changed in place, such as state in a reducer. The cost is a shallow copy on every update. For large dictionaries that change often, that cost can matter, and a Map that you mutate in a controlled place may be a better fit.
Readonly is shallow
A read-only dictionary of arrays does not stop you from changing the arrays:
type ShallowGroups = Readonly<Record<string, number[]>>;
type DeepGroups = { readonly [group: string]: readonly number[] };
function addMember(groups: ShallowGroups, name: string, id: number): void {
groups[name]?.push(id); // compiles: the arrays are still mutable
}
function countMembers(groups: DeepGroups, name: string): number {
// groups[name]?.push(1); // Error: Property 'push' does not exist on type 'readonly number[]'.
return groups[name]?.length ?? 0;
}
const groups: ShallowGroups = { admins: [1, 2] };
addMember(groups, "admins", 3);
console.log(countMembers(groups, "admins")); // 3ShallowGroups blocks groups["admins"] = [] but allows groups["admins"].push(3). To protect the contents, make the value type read-only as well, as DeepGroups does with readonly number[]. For nested objects, add readonly to their properties too. TypeScript has no built-in deep-readonly type, and hand-written recursive versions have their own edge cases with functions, Map, and Set.
The gotcha: readonly does not affect assignability
This is the most common surprise. TypeScript does not treat readonly as part of type compatibility. A read-only dictionary can be passed to a parameter that expects a mutable one, and the compiler says nothing:
interface ReadonlyDict {
readonly [key: string]: number;
}
function bump(d: { [key: string]: number }): void {
d["max"] = 99;
}
const limits: ReadonlyDict = { max: 10 };
bump(limits); // compiles without error
console.log(limits["max"]); // 99The guarantee holds only along paths where the read-only type is visible. If the value passes through a function with a mutable parameter type, or through a type assertion, the protection is gone. The same applies to readonly properties and ReadonlyArray.
Compile-time versus runtime
Type annotations are erased when TypeScript compiles to JavaScript, so a read-only type adds no runtime protection. If you need writes to fail at runtime, use Object.freeze. Its type signature returns Readonly<T>, so the runtime and compile-time guarantees line up.
"use strict";
const base: Record<string, number> = { max: 10 };
const frozen = Object.freeze(base); // Readonly<Record<string, number>>
const writable = frozen as Record<string, number>;
try {
writable["max"] = 20;
} catch (error) {
console.log(error instanceof TypeError); // true
}
console.log(frozen["max"]); // 10Three details matter here:
- In strict mode code, writing to a frozen object throws a
TypeError. In sloppy mode the write is silently ignored. ES modules and classes are always strict, and a TypeScript file withstrictoralwaysStrictenabled compiles with"use strict". Object.freezefreezes the object you pass in, not a copy. In the example,baseis frozen too.- Freezing is shallow, just like
readonly. Nested objects and arrays stay mutable unless you freeze them as well.
The figure compares the two layers of protection.
Constants with as const
When the dictionary is a fixed constant with known keys, as const makes the object literal read-only and keeps the exact keys and values. Adding satisfies checks it against the dictionary shape you expect:
const defaults = { max: 10, min: 1 } as const satisfies Record<string, number>;
type DefaultKey = keyof typeof defaults; // "max" | "min"
console.log(defaults.max); // 10
// defaults.max = 20; // Error: Cannot assign to 'max' because it is a read-only property.This combination needs TypeScript 4.9 or later. The result is not an index-signature type. It has two named properties, so defaults.typo is a compile error and keyof gives you a precise union of keys. That is usually what you want for configuration known at write time. A read-only index signature is the better fit when the keys are only known at runtime, for example a table loaded from a file.
Interaction with noUncheckedIndexedAccess
The two features are independent. readonly controls writes, and noUncheckedIndexedAccess controls the type of reads. With both enabled, limits["max"] is number | undefined and you still need a check before using it:
interface ReadonlyDict {
readonly [key: string]: number;
}
function maxOrDefault(limits: ReadonlyDict): number {
const max = limits["max"]; // number | undefined with noUncheckedIndexedAccess
return max ?? 100;
}
console.log(maxOrDefault({ max: 10 })); // 10
console.log(maxOrDefault({})); // 100A read-only dictionary can still be missing a key. The readonly modifier says nothing about which keys exist.
Choosing a read-only strategy
- Use
readonly [key: string]: VorReadonly<Record<string, V>>for function parameters and for data that your own code only reads. This costs nothing at runtime. - Add
readonlyto the value type (readonly V[], or read-only properties) when the values must be protected as well. - Use
as const satisfies Record<string, V>for constants whose keys are known when you write the code. - Add
Object.freezewhen untrusted or loosely typed code could reach the object, and you want writes to fail at runtime. Remember it is shallow. - Consider a
Mapbehind a class with only read methods when you need a collection that cannot be mutated through its public interface at all. The class, notreadonly, enforces this.
Exercise
Given interface Table { readonly [key: string]: number } and const t: Table = { a: 1 };, which of these lines produce a compile error? (1) t["a"] = 2; (2) const copy: Table = { ...t, b: 3 }; (3) function f(x: { [k: string]: number }) { x["a"] = 5; } f(t); (4) t.b = 3;
Show answer
Lines 1 and 4 are errors, because both write through a readonly index signature. Line 2 is fine, since it builds a new object instead of changing t. Line 3 also compiles, because TypeScript does not consider readonly when checking assignability. Calling f(t) therefore changes t["a"] to 5 at runtime.
Exercise
You have const groups: Readonly<Record<string, string[]>> = { staff: ["ann"] }; and you want the compiler to reject groups["staff"]?.push("bob"). What change to the type achieves that, and why does the original type allow the call?
Show answer
Change the type to { readonly [group: string]: readonly string[] }, or Readonly<Record<string, readonly string[]>>. The original type marks only the dictionary slots as read-only. The arrays stored in them are ordinary mutable string[] values, so push is allowed. Making the value type readonly string[] removes push from the array type.