
Objects whose keys are decided at runtime are one of the most common shapes in application data, and TypeScript offers four competing ways to type them: Record<K, V>, index signatures, plain interfaces, and the Map class. Each option answers a different question about the key space — whether it is a known finite set, a fully open range, or a fixed heterogeneous shape — and each makes different trade-offs between compile-time coverage, value-type precision, serialization, and runtime behavior. Picking the wrong container produces real failure modes: silent typos, undefined crashes on missing lookups, and awkward conversions at JSON boundaries. This article compares the four options directly: why Record enforces full key coverage for a known union of keys while index signatures do not, when a fixed interface is the better fit, and when Map's semantics make it the right container. It also shows how the satisfies operator, introduced in TypeScript 4.9, verifies a dictionary literal against a Record type without widening its inferred literal types. The intended audience is TypeScript developers who design and maintain dictionary-shaped data such as permission tables, caches, configuration maps, and lookup registries.

TypeScript provides four ways to model key‑value collections: Record<K, V>, index signatures ({ [key: string]: V }), plain interfaces, and the built‑in Map class. Which one you pick depends on the shape of the key space, not on stylistic preference. The following taxonomy separates the common runtime scenarios and shows how each container aligns with them.
When the possible keys are a finite set known at compile time (e.g., "admin" | "user" | "guest"), a Record is the natural fit. Record<K, V> requires full coverage of every member of the union, so a missing entry triggers a compile‑time error and IDEs can autocomplete all keys. This exhaustiveness prevents silent typos that index signatures would otherwise allow — the type system forces you to enumerate every required property 【source https://strapi.io/blog/typescript-dictionary-guide】. Because the key type K must be assignable to string, number or symbol, Record can only model the runtime‑compatible property names that JavaScript objects support 【source https://www.convex.dev/typescript/core-concepts/maps-sets-specialized-types/typescript-record】.
If keys arrive from user input, database IDs, cache identifiers, or any other dynamic source, the set is unbounded. An index signature ({ [key: string]: V }) or a plain interface with an index signature expresses this openness; any string key is accepted without requiring enumeration. Record<string, V> is essentially shorthand for such an index signature and can be written inline without an extra alias 【source https://blog.logrocket.com/how-to-dynamically-assign-properties-object-typescript】. This approach is ideal for structures that will be serialized to JSON, spread with {...obj}, or accessed via dot notation, but it sacrifices compile‑time checks for individual required keys.
Sometimes an object appears dynamic because its keys are computed once (e.g., the result of Object.fromEntries on a known list). The shape is actually static: each key has a distinct, possibly different, value type. Declaring a regular interface with explicit property signatures conveys this heterogeneity best, because a single homogeneous value type (V) would be too coarse. The interface also preserves exact literal types for each property, which Record would otherwise widen.
| Scenario | Recommended container |
|---|---|
| Known union of keys | Record<K, V> |
| Arbitrary runtime keys | Index signature / Record<string, V> |
| Fixed mixed‑type shape | Plain interface (or type literal) |
| Need non‑string keys, ordering, or efficient mutations | Map<K, V> (covers cases where 1‑3 don’t apply) |
Choosing the correct container before writing any type eliminates three common failure modes:
Record is caught at compile time.undefined for any unexpected key.Map instances must be transformed to plain objects for serialization.By mapping the data’s key‑space situation to its best‑fit TypeScript construct, you gain stronger type safety, clearer intent, and fewer runtime surprises.

Record Enforces Full Key Coverage Where Index Signatures Don’tWhen the first type argument of Record<K, V> is a finite union of literal types (or an enum), TypeScript treats the utility as a mapped type: every member of K becomes a required property of the resulting object type. The compiler therefore checks that all keys are present in any object literal assigned to the Record.
type ColourVariant =
| "primary" | "secondary" | "tertiary"
| "alert" | "error" | "light" | "dark";
const palette = {
primary: "green",
secondary: "yellow",
tertiary: "white",
alert: "orange",
error: "red",
dark: "black",
} satisfies Record<ColourVariant, string>;
The above fails with
Property 'light' is missing in type … but required in type
'Record<ColourVariant, string>'.
The same behaviour appears for any union of string literals, e.g. type Status = "pending" | "approved" | "rejected" – omitting "rejected" produces a missing‑property error Source 1.
Because the keys are known ahead of time, IDEs can present an exhaustive autocomplete list, turning a simple typo into a compile‑time diagnostic. Strapi’s best‑practice guide highlights this as a primary advantage over plain index signatures, which accept arbitrary strings without warning Source 2.
The same rule applies when K is an enum.
enum HttpMethod { GET = "GET", POST = "POST", PUT = "PUT", DELETE = "DELETE" }
type Handlers = Record<HttpMethod, (req: any) => void>;
const api: Handlers = {
[HttpMethod.GET]: () => {},
[HttpMethod.POST]: () => {},
[HttpMethod.PUT]: () => {},
// missing HttpMethod.DELETE → compile error
};
Leaving out any enum member, or adding an unexpected key, triggers a compile‑time error, ensuring the handler map stays in sync with the supported HTTP verbs Source 3.
Record only enforces exhaustive coverage when its key type is a finite union. When the key type is the broader string (or number), Record<string, V> collapses to an index signature‑like type—no keys are required, and any extra property is accepted. Some sources note this behaviour and warn that Record<string, V> “does not force you to include every key from the union” because there is no union to begin with Source 4. Consequently, the missing‑key errors described above do not appear for Record<string, V>; developers must use other techniques (e.g., satisfies with a narrower key type) when they need full coverage.
| Aspect | Record<FiniteUnion, V> | Index signature ([k: string]: V) |
|---|---|---|
| Key completeness | All union members required (compile error if absent) | No completeness check |
| Typo safety | Misspelled keys are rejected at compile time | Misspellings silently accepted |
| IDE support | Autocompletes exact keys | Autocompletes generic string |
| When to use | Fixed, known key set (e.g., permission tables, HTTP handlers) | Truly open dictionaries where keys are truly dynamic |
| Exception | Record<string, V> behaves like an index signature | — |
Thus, Record gives you exhaustive, type‑safe dictionaries only when the key space is a finite union or enum. Outside that scenario it degrades to the permissive behaviour of an index signature, and developers must choose the appropriate construct to avoid silent runtime failures.

When a dictionary’s keys cannot be enumerated at compile time, an index signature ({ [key: string]: T }) is the idiomatic way to express that openness. As the Convex documentation advises, “use an index signature … when the set of keys is truly dynamic or unknown at compile time” and illustrates it with a DynamicCache interface that accepts any string key mapped to a string value【source】(https://www.convex.dev/typescript/core-concepts/maps-sets-specialized-types/typescript-record)【source】.
| Benefit | Explanation |
|---|---|
| Natural property syntax | Keys can be accessed with dot notation (if not prohibited) or bracket notation, just like plain objects, making the API familiar to JavaScript developers. |
| JSON‑friendly | Objects with index signatures serialize and deserialize with JSON.stringify/JSON.parse without extra transformation. |
| Spread & merge support | The usual object spread ({ ...obj, newKey: value }) works without needing to convert to Map. |
| Uniform value type | The compiler enforces that every present key holds a value of type T; a Record<string, string> literal can be written directly as const organization: Record<string, string> = {}【source】(https://blog.logrocket.com/how-to-dynamically-assign-properties-object-typescript/)【source】. |
string | number), pushing narrowing logic onto every consumer.noPropertyAccessFromIndexSignature compiler option (available in tsconfig.json) forbids dot access on index‑signature properties, forcing explicit bracket notation (obj[key]). This makes dynamic access visually obvious in code reviews, but it is not enabled by default, so its effect is configuration‑sensitive【source】(https://www.totaltypescript.com/books/total-typescript-essentials/configuring-typescript)【source】.If the codebase frequently accesses dictionary entries with fixed dotted names (e.g., config.apiUrl), the key set is likely closed. In that case a Record<"apiUrl" | "timeout", string> provides exhaustiveness checking and better IDE autocomplete.
Conversely, for truly open maps—such as caches keyed by session identifiers, form‑field values parsed into { [fieldName: string]: string }, or lookup tables built from external data—an index signature remains the most straightforward and type‑safe choice.
interface SessionCache {
[sessionId: string]: string; // any session ID maps to cached data
}
const cache: SessionCache = {};
function store(id: string, data: string) {
cache[id] = data; // bracket notation works regardless of the actual key
}
In summary, index signatures are the honest answer when the key space is genuinely unknown. They give you the flexibility of plain objects while still guaranteeing that every value conforms to the declared type, at the cost of weaker key‑level safety. Adjusting tsconfig.json with noPropertyAccessFromIndexSignature can mitigate accidental dot‑access mistakes, and switching to Record should be considered whenever the key universe becomes closed.

Record<'apiUrl' | 'timeout' | 'retries', string | number> guarantees that every key in the union is present, but it also forces all values into the same string | number union.
The per‑field precision is lost:
type Config = Record<'apiUrl' | 'timeout' | 'retries', string | number>;
If apiUrl is accidentally assigned a number, the compiler cannot flag the mismatch because the type permits it. The Convex best‑practice guide recommends an explicit interface for such heterogeneous shapes, because each property can be checked independently — apiUrl stays a string, timeout a number, and retries a number Convex.
interface Config {
apiUrl: string;
timeout: number;
retries: number;
}
Only when all values truly share one type should Record be used. For a small, fixed configuration object the interface also yields clearer IDE autocomplete and more accurate JSDoc generation.
If you already have an interface and need a derived dictionary (for example, a feature‑flag map where the keys are the same as the original fields), a mapped type gives a closed key set:
type FlagMap = { [K in keyof Config]?: boolean };
Because the key set is limited to keyof Config, the compiler issues excess‑property errors (TS2322) for any unknown key. Jake Trent’s comparison shows that Record<string, boolean> accepts any string key, while the mapped type raises a diagnostic for stray properties — the former is an open‑ended catch‑all, the latter a constrained view Jake Trent.
This pattern is useful for:
GET, POST, …) has a distinct signature.| Shape | Value‑type uniformity | Recommended type |
|---|---|---|
| Fixed set of fields, different types per field | Heterogeneous | Interface (or type alias) |
| Finite union of keys, same value type for every key | Homogeneous | Record<K, V> |
| Need a derived view that restricts keys to an existing interface | Closed‑set, possibly optional | Mapped type { [K in keyof I]?: V } |
| Keys truly dynamic, unknown at compile time | Open‑ended | Index signature { [key: string]: V } or Map for runtime safety |
When both an interface and a Record could model the data, the interface wins on precision (each property is validated against its own type), while Record wins when you require a uniformity guarantee across all entries. Choosing the right container prevents silent typos, eliminates runtime undefined crashes, and keeps JSON serialization straightforward.

When a dictionary is typed as Record<string, User>, TypeScript assumes every possible string key yields a User. At runtime, however, a missing key returns undefined, so a direct property access such as cache["nonexistent"].name throws a TypeError despite compiling without error【https://www.convex.dev/typescript/core-concepts/maps-sets-specialized-types/typescript-record】.
The compiler can be instructed to treat indexed access more conservatively. The noUncheckedIndexedAccess flag rewrites the inferred type of obj[key] (or arr[i]) to T | undefined instead of plain T, forcing an explicit check before the value is used【https://www.totaltypescript.com/books/total-typescript-essentials/configuring-typescript】. This flag is optional and not part of the strict bundle, so its effect varies between projects; the 2026 Node‑with‑TypeScript guide recommends enabling it alongside strict and strictNullChecks for production code【https://novasphereailab.com/blog/nodejs-with-typescript-guide-2026】.
| Approach | How it works | When to use | ||
|---|---|---|---|---|
| Optional chaining / nullish coalescing | cache["x"]?.name ?? "unknown" short‑circuits on undefined and supplies a fallback. | Quick, ad‑hoc fixes where missing entries are acceptable. | ||
PartialRecord helper | ```ts\ntype PartialRecord<K extends string | number | symbol, V> = Partial<Record<K, V>>;\nconst statusMessages: PartialRecord<Status, string> = { pending: "Waiting" };\n```<br>Combines Partial with Record so the type explicitly includes undefined for absent keys【https://www.convex.dev/typescript/core-concepts/maps-sets-specialized-types/typescript-record】. | Known union of keys where some entries are intentionally absent. |
Map | new Map<string, User>() returns `User | undefinedfromget`, making the undefined case part of the API contract. | Open key space or when you need the richer runtime semantics of Map (iteration order, size, explicit has). |
Partial<Record<KeyUnion, V>> (or the PartialRecord alias) so the type system reflects the optionality.noUncheckedIndexedAccess and handle undefined everywhere, or switch to Map for a design that acknowledges missing entries.As a convention, treat direct reads from an unchecked Record<string, T> as unsafe; always guard with ?., ??, a Partial wrapper, or a Map to avoid silent runtime crashes.

Map Is the Better Container| Aspect | Map | Plain‑object dictionary (Record / index signature) | |
|---|---|---|---|
| Allowed key types | Any value – primitives and objects, functions, even other Maps. | Only string / number / symbol; other values are coerced to strings. [Convex] | |
| Missing‑key handling | .get(k) returns `V | undefined`, so the compiler forces a check before use. | obj[k] yields undefined silently; no compile‑time warning unless --noUncheckedIndexedAccess is enabled. |
| Iteration | Built‑in iterators: for…of, .forEach, .keys(), .values(), .entries(). | Need Object.keys/values/entries which allocate temporary arrays. | |
| Size | Constant‑time .size property. | Computed via Object.keys(obj).length (O(n) and does not include symbol keys). | |
| Insertion order | Guaranteed order of iteration exactly as entries were added. | Historically unordered; modern engines preserve order for string keys but the spec does not guarantee it. | |
| Mutation performance | Optimised for frequent set/delete – the internal hash table avoids the re‑allocation cost of objects. | Adding/deleting properties on an object causes hidden‑class changes and can be slower for large, mutable collections. | |
| Read performance | Faster for large collections (thousands of entries) where the hash lookup cost is amortised. | Faster for tiny, static objects because the overhead of creating a Map outweighs any lookup benefit. The Convex guidance notes a rough “under‑100‑entries” heuristic, and a Medium benchmark shows Map adding 100 k entries in ~12 ms vs ~18 ms for an object. [Convex] [Medium] | |
| Security | No prototype chain – map.has('toString') returns false. | Inherits Object.prototype; keys such as "toString" or "__proto__" collide with inherited properties and open a prototype‑pollution surface. [Medium] | |
| Serialization | Not directly JSON‑serialisable; you must convert (Array.from(map.entries()) or a manual object reduction) before JSON.stringify. | Works out‑of‑the‑box with JSON.stringify and supports spread ({...obj}) syntax. |
Choose Map when any of the following applies:
Stay with plain objects when you need:
In many codebases the pragmatic pattern is to start with a plain object for simple configuration data and migrate to a Map once the shape becomes dynamic, the key type expands beyond strings, or mutation intensity rises. The satisfies operator (TS 4.9) can still be used to validate a literal against a Record before you decide to convert it to a Map for runtime use.

The satisfies operator, added in TypeScript 4.9, is a compile‑time‑only construct; the syntax is stripped during transpilation and has no runtime footprint. Its purpose is to let you check that a value conforms to a target type while keeping the value’s inferred literal types unchanged — a gap that plain Record<K, V> annotations leave open.
// Without satisfies – the literals are widened to `string`
const config: Record<string, string> = {
theme: 'dark',
lang: 'en',
};
config.theme; // string
// With satisfies – the literals stay exact
const config = {
theme: 'dark',
lang: 'en',
} satisfies Record<string, string>;
config.theme; // 'dark' (literal type)
In the first form the object is forced into the Record shape, but the compiler widens each property to the generic value type (string). The satisfies version still validates the shape against Record<string, string> without that widening, preserving 'dark' and 'en' for later use — for example in switch statements, discriminated unions, or API contracts where the precise string matters 【source1】.
const StatusEnum = {
Success: "Success",
Pending: "Pending",
Failed: "Failed",
} as const satisfies Record<string, string>;
Here as const freezes the literal values, and satisfies Record<string, string> guarantees every property is a string while leaving the literals ("Success" etc.) intact 【source2】. Replacing string with number gives a numeric dictionary without extra code.
When a required key is absent, the compiler produces a pinpoint error:
Property 'light' is missing in type '{ primary: string; … }'
but required in type 'Record<ColourVariant, string>'.
Such messages are more actionable than the generic “type ‘{ … }’ is not assignable” errors that arise from plain Record annotations 【source3】.
When to use:
switch, derived unions).In contexts like status maps, theme tables, i18n dictionaries, or enum‑replacement objects, satisfies offers the strictness of a Record check while retaining the expressive power of literal types.

Fixed heterogeneous shape – Use a plain interface.
When the object has a known set of fields with different value types, a literal interface preserves per‑field precision. Record would widen each field to the same value type, losing the heterogeneity.
Finite, known key union – Prefer Record<KeyUnion, V>.
Record forces a value for every key, preventing silent omissions.
Partial<Record<KeyUnion, V>> or a custom PartialRecord helper.as const and adding the satisfies operator (requires TypeScript 4.9+)¹.Open key space (any string) – Use an index signature or the shorthand Record<string, V>.
Both give the same compile‑time shape; choose the form you find more readable.
noUncheckedIndexedAccess (and optionally noPropertyAccessFromIndexSignature) to make obj[key] type V | undefined, enforcing explicit handling of missing entries².obj[key]?.prop ?? default) or consider switching to a Map (see step 4).Non‑string keys, insertion‑order, frequent mutation, size queries, or untrusted keys – Choose Map.
Map accepts any value as a key, preserves insertion order, offers O(1) set/delete, and has a built‑in size property.
Object.fromEntries(map) or Array.from(map.entries()) because JSON.stringify on a Map yields an empty object³.Keys originating from external input – Validate before assignment.
*Security guidance recommends whitelisting allowed keys and rejecting dangerous names such as __proto__, constructor, and prototype*⁴.
Object.create(null)) to avoid prototype‑pollution attacks⁵.Hard constraint: If the data will be serialized with JSON.stringify, prefer plain objects (interfaces, Record, or index signatures) because they serialize out‑of‑the‑box, whereas Map requires explicit conversion.
Overall ordering: Choose by key space first, then value homogeneity, and finally runtime behavior (mutation patterns, serialization, security).