Mapped Types vs Index Signatures
What you'll learn: How to decide between mapped types and index signatures when you need flexible object shapes with dynamic keys.
Both mapped types and index signatures let you define objects with dynamic properties, but they serve different purposes and offer different levels of type safety.
When to Use Index Signatures
Index signatures are best when you don't know the property names in advance and treat all values uniformly:
// Index signature: any string key → number value
type UserScores = {
[username: string]: number;
};
const scores: UserScores = {
alice: 95,
bob: 87,
charlie: 92
};
This works great for truly dynamic data like user-generated keys, configuration dictionaries, or API responses where keys vary at runtime.
When to Use Mapped Types
Mapped types are better when you transform or constrain a known set of keys:
type Permissions = "read" | "write" | "delete";
// Mapped type: iterate over known keys
type PermissionFlags = {
[K in Permissions]: boolean;
};
const userPerms: PermissionFlags = {
read: true,
write: false,
delete: false
};
Here, you must include all three properties. Mapped types give you exhaustiveness checking that index signatures can't provide.
The Key Difference
Index signatures say "accept any key of this type." They're open-ended and permissive.
Mapped types say "iterate over these specific keys." They're closed and precise.
If you have a finite set of possible keys (even if computed with keyof), mapped types give you stronger guarantees. If you genuinely have unlimited runtime keys, index signatures are the right choice.
Key Takeaway: Use index signatures for truly dynamic, open-ended objects; use mapped types when transforming or constraining known key sets for type safety and exhaustiveness.