Sub topic 8
Readonly Dictionaries
Prerequisites: basic TypeScript interfaces, type aliases, index signatures, and the undefined type. You should also know that JavaScript objects can be accessed with dot notation, such as settings.theme, or bracket notation, such as settings["theme"].
A readonly dictionary is an object type that allows lookup but prevents assignment through its index signature. Use the readonly modifier before the index signature:
interface ReadonlyDict {
readonly [key: string]: number;
}
const limits: ReadonlyDict = {
min: 1,
max: 10,
};
console.log(limits["min"]); // 1
console.log(limits.max); // 10
// limits["max"] = 20;
// Error: Index signature in type 'ReadonlyDict' only permits reading.The restriction applies to both bracket and dot notation when the property is treated as an indexed value. The object can be read, but TypeScript rejects assignments through the dictionary type.
Why readonly matters
A mutable dictionary lets any part of a program replace a value:
interface Scores {
[name: string]: number;
}
const scores: Scores = { alice: 90 };
scores["alice"] = 95;
scores.bob = 80;This is useful when the dictionary is intentionally updated. It is risky when a function should only inspect data. A readonly parameter documents that the function does not modify the dictionary:
interface Scores {
readonly [name: string]: number;
}
function printScore(scores: Scores, name: string): void {
const score = scores[name];
if (score !== undefined) {
console.log(`${name}: ${score}`);
}
}
const scores: Scores = { alice: 90 };
printScore(scores, "alice");A readonly index signature prevents accidental writes inside printScore. It does not make a copy of the object.
flowchart TD
A[Readonly dictionary] --> B[Read with key]
A --> C[Write with key]
B --> D[Allowed by TypeScript]
C --> E[Rejected by TypeScript]
A --> F[Runtime JavaScript object]
F --> G[Still mutable unless frozen]Readonly is shallow
readonly protects the property assignment itself. It does not recursively freeze values stored in the dictionary.
interface MutableUser {
name: string;
}
interface UserDirectory {
readonly [id: string]: MutableUser;
}
const users: UserDirectory = {
u1: { name: "Ada" },
};
// users["u1"] = { name: "Grace" }; // Error
users["u1"].name = "Grace"; // AllowedThe dictionary cannot replace the user object at u1, but the user object can still change. To protect the nested value, make its properties readonly too:
interface User {
readonly name: string;
}
interface ReadonlyUserDirectory {
readonly [id: string]: User;
}
const users: ReadonlyUserDirectory = {
u1: { name: "Ada" },
};
// users["u1"].name = "Grace"; // Error> callout note > A readonly index signature is a compile-time rule. It does not stop JavaScript code, type assertions, or other aliases from changing the object at runtime.
Named properties can differ
A readonly index signature constrains indexed access. Explicit properties must still have a compatible value type, but their own declarations can be mutable unless you mark them readonly:
interface Settings {
readonly [key: string]: string | number;
version: string;
retries: number;
}
const settings: Settings = {
version: "1.0",
retries: 3,
};
settings.retries = 4; // Allowed through the named property
// settings["retries"] = 5; // Error through the readonly index signatureThis difference can be surprising. If every property must be immutable, mark the named properties readonly as well, or expose the value through a fully readonly type.
Related readonly types
Readonly<Record<string, T>> is another way to describe a readonly dictionary:
type Limits = Readonly<Record<string, number>>;
const limits: Limits = {
timeout: 30,
};
// limits.timeout = 60; // Error
console.log(limits.timeout);For known keys, a mapped type gives more precise control:
type FeatureFlags = {
readonly [K in "search" | "reports"]: boolean;
};
const flags: FeatureFlags = {
search: true,
reports: false,
};Use a readonly index signature when keys are open-ended. Use a mapped type when the allowed keys are a known union.
Runtime immutability
If runtime code must also reject changes, use Object.freeze:
interface ReadonlyConfig {
readonly [key: string]: string | number;
}
const config: ReadonlyConfig = Object.freeze({
port: 8080,
mode: "production",
});
console.log(config.port);Object.freeze is shallow, just like the basic readonly type. Nested objects need their own freezing or a deep-freeze utility.
Exercise
What does a readonly index signature prevent, and what does it not prevent?
Show answer
It prevents TypeScript assignments through dictionary keys, such as dict["key"] = value. It does not recursively freeze nested values or guarantee runtime immutability.