Alternatives to Index Signatures
You'll learn when to replace flexible index signatures with more precise alternatives for better type safety.
The Problem with Index Signatures
Index signatures like [key: string]: number are convenient because they accept any string key. But this flexibility comes at a cost: TypeScript can't help you catch typos or invalid keys. When you access obj.nme instead of obj.name, the compiler stays silent — you just get back the value type (or undefined).
Map<string, ValueType> for True Dictionaries
When you're working with genuinely dynamic keys (runtime user input, API data, etc.), use Map instead of an index signature:
// Weak: allows any key, returns number | undefined
const scores: { [key: string]: number } = {};
// Stronger: explicit Map with clear types
const scores = new Map<string, number>();
scores.set("alice", 100);
const aliceScore = scores.get("alice"); // number | undefined
Map makes the dynamic nature explicit and provides a safer API (get, has, set) rather than plain property access.
Union Types for Known Keys
When your keys are finite and known, don't use index signatures at all — use a union type:
// Weak: accepts any string
type Config = { [key: string]: boolean };
// Strong: only valid keys accepted
type Config = {
darkMode: boolean;
notifications: boolean;
analytics: boolean;
};
This way, config.darkMood becomes a compile error instead of returning undefined at runtime.
Key Takeaway: Prefer Map<K, V> for truly dynamic data and specific union types for known properties — index signatures should be your last resort, not your first choice.