Record vs Index Signatures
What you'll learn: How Record<K, T> and index signatures both create key-value mappings, and when to choose each for better type safety and clarity.
Both Record and index signatures let you type objects with dynamic keys, but they serve different purposes and offer different levels of control.
The Core Difference
An index signature says "this object can have any key matching this pattern, with values of this type":
type StringMap = {
[key: string]: number;
};
const scores: StringMap = {
alice: 95,
bob: 87,
charlie: 92
};
The Record utility says "this object has exactly these known keys, all with the same value type":
type UserScores = Record<'alice' | 'bob' | 'charlie', number>;
const scores: UserScores = {
alice: 95,
bob: 87,
charlie: 92
// TypeScript knows exactly which keys exist
};
When to Choose Record
Use Record when:
- You know the exact set of keys upfront
- You want autocomplete for property names
- You need exhaustiveness checking (all keys must be present)
Use index signatures when:
- Keys are truly dynamic or user-provided
- You want to allow any matching key to be added
- The set of keys is open-ended
The Flexibility Trade-off
Index signatures are more flexible but less precise. Record gives you compile-time guarantees about which keys exist, while index signatures only guarantee value types.
Key Takeaway: Use Record<K, T> when you know your keys; use index signatures when keys are truly dynamic and unpredictable.