Sub topic 12
Choosing the Right Approach for Dictionary Objects
Assume you know basic TypeScript types, interfaces, type aliases, union types, and JavaScript property access. This chapter compares index signatures, Record, mapped types, and Map so you can choose the right representation for a collection of key-value pairs.
Start with the shape of the keys
Use an index signature when an object can receive arbitrary keys and all values follow one type:
interface Scores {
[name: string]: number;
}
const scores: Scores = {
alice: 90,
bob: 85,
};
scores.carol = 88;Use Record when you want the same idea in a type alias:
type Scores = Record<string, number>;These types describe open dictionaries. A lookup such as scores["unknown"] is allowed because the key is not limited to a fixed list.
Use a mapped type when the valid keys come from a union of literal types. A literal type represents one exact value:
type Environment = "development" | "production";
type URLs = {
[name in Environment]: string;
};
const urls: URLs = {
development: "http://localhost:3000",
production: "https://example.com",
};This object must contain both keys. Record<Environment, string> expresses the same requirement:
type URLs = Record<Environment, string>;Use Partial when those known keys are optional:
type OptionalURLs = Partial<Record<Environment, string>>;
const urls: OptionalURLs = {
development: "http://localhost:3000",
};Compare the choices
| Approach | Best for | Key rules | Missing lookup | Column |
|---|---|---|---|---|
| Index signature | Open object dictionaries | Usually any string, number, or symbol | Use `noUncheckedIndexedAccess` for `undefined` | |
| `Record` | Open or finite key sets | `Record<string, T>` is open; `Record<K, T>` can be exact | Object property lookup | |
| Mapped type | Transforming a known key union | Keys come from an existing type | Object property lookup | |
| `Map` | Frequently changing collections or non-string keys | Any key type, including objects | `get` returns `T | undefined` |
A Record with a union is often the clearest choice when every known key is required. A mapped type is more useful when you need modifiers or transformations:
type Feature = "search" | "export";
type FeatureConfig = {
[key in Feature]?: {
enabled: boolean;
};
};
const config: FeatureConfig = {
search: { enabled: true },
};Consider runtime behavior
Objects inherit properties such as toString. If arbitrary input keys can come from users or external data, check own properties with Object.hasOwn:
const prices: Record<string, number> = {
book: 12,
};
function getPrice(name: string): number | undefined {
if (Object.hasOwn(prices, name)) {
return prices[name];
}
return undefined;
}
console.log(getPrice("book")); // 12
console.log(getPrice("pen")); // undefinedEnable noUncheckedIndexedAccess when missing keys are possible. TypeScript then treats indexed reads as possibly undefined, requiring code to handle that case.
Choose Map when keys are not naturally strings, when insertion order matters, or when you frequently add, remove, and count entries:
const visits = new Map<string, number>();
function recordVisit(page: string): void {
visits.set(page, (visits.get(page) ?? 0) + 1);
}
recordVisit("/home");
recordVisit("/home");
console.log(visits.get("/home")); // 2Map keeps keys separate from object prototypes and provides operations such as has, get, set, and delete. Its get method still returns undefined when a key is absent, so callers must handle a missing value.
A practical decision process
Use an index signature or Record<string, T> for a JSON-like object with arbitrary string keys. Use Record<K, T> or a mapped type for a controlled set of keys. Use Map<K, V> for dynamic collections, object keys, or APIs that need explicit collection operations.
Exercise
You need settings for exactly "darkMode" and "fontSize", but either setting may be omitted. Which type is a good fit?
Show answer
Use Partial<Record<"darkMode" | "fontSize", boolean | number>>, or a mapped type with optional properties. The finite key union documents the allowed names, and Partial permits omission.