Index Signatures vs Mapped Types
What you'll learn: When to choose index signatures for truly dynamic keys versus mapped types for transforming known key sets.
The Core Difference
Both index signatures and mapped types let you describe objects with many properties, but they serve different purposes:
Index signatures are for objects where you genuinely don't know what the keys will be at compile time. Think of a user preferences object where users can define their own setting names.
Mapped types are for transforming a known set of keys in a systematic way. Think of taking existing properties and making them all optional or readonly.
When to Use Index Signatures
Use index signatures when:
- Keys are completely dynamic (user input, API responses with arbitrary fields)
- You're modeling dictionaries or maps
- You don't know key names ahead of time
// Truly dynamic keys from user input
type UserSettings = {
[settingName: string]: boolean | string | number;
};
const settings: UserSettings = {
darkMode: true,
fontSize: 14,
theme: "ocean"
};
When to Use Mapped Types
Use mapped types when:
- You have a specific set of known keys to transform
- You're creating variations of existing types
- You need to apply a transformation (like making properties readonly or optional) to a defined key set
type User = {
name: string;
age: number;
};
// Mapped type: transforming KNOWN keys
type ReadonlyUser = {
readonly [K in keyof User]: User[K];
};
Key Takeaway: Use index signatures for unknown, dynamic keys; use mapped types when transforming a specific, known set of keys with a systematic pattern.