Sub topic 3
Readonly Dictionaries and Alternatives
Assume you know basic TypeScript types, interfaces, union types, and JavaScript property access.
Readonly dictionaries
A readonly index signature allows code to read values through arbitrary keys but prevents assignments through the dictionary.
interface Limits {
readonly [key: string]: number;
}
const limits: Limits = { timeout: 30 };
console.log(limits["timeout"]);
// limits["timeout"] = 60; // Error: only reading is allowedThis protects the type-level view of the object. It does not freeze the object at runtime. Code with another reference can still mutate the object unless you use Object.freeze.
Pattern index signatures
A template literal pattern restricts keys to a naming convention. This is useful for HTML-style data attributes or environment variables.
interface DataAttributes {
[key: `data-${string}`]: string;
}
const attributes: DataAttributes = {
"data-id": "42",
"data-role": "admin",
};
// "role": "admin" would be rejected.The pattern is narrower than [key: string], which accepts every string key.
Record and mapped types
Record<K, V> describes an object whose keys are K and whose values are V.
type Level = "low" | "high";
const limits: Record<Level, number> = {
low: 1,
high: 10,
};
const optionalLimits: Partial<Record<Level, number>> = {
low: 1,
};A union of literal keys requires every key. Partial makes those keys optional. A mapped type gives more control when each key needs a related type or modifier:
type Flags = {
[K in Level]?: boolean;
};When to use `Map` instead
Use Map<K, V> when keys change frequently, can have types other than strings, or when you want dictionary operations without object prototypes.
const counts = new Map<string, number>();
for (const word of ["a", "b", "a"]) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
console.log(counts.get("a")); // 2Map.get returns V | undefined, so missing entries are explicit.
Choosing the right approach
| Requirement | Suitable choice |
|---|---|
| Arbitrary string keys on an object | Index signature |
| A fixed set of known keys | `Record` or mapped type |
| Keys following a naming pattern | Template literal index signature |
| Frequent insertion, deletion, or non-string keys | `Map` |
| Read-only access through arbitrary keys | `readonly` index signature |
Exercise
Which type best describes an object with exactly "low" and "high" numeric keys?
Show answer
Record<"low" | "high", number>.