Common Index Signature Pitfalls
You'll learn how index signatures can accidentally make your code less safe by accepting typos and forcing you to handle undefined everywhere.
The Hidden Danger
Index signatures are powerful, but they come with a major pitfall: they're too permissive. When you write [key: string]: number, TypeScript assumes every possible string property returns a number. This means typos, random property names, and non-existent keys all appear valid to TypeScript.
Problem 1: Swallowing Typos
const scores: { [key: string]: number } = {
math: 95,
science: 88
};
// Typo! TypeScript thinks this is fine
const grade = scores.sceince; // Type: number (but actually undefined!)
TypeScript infers grade as number, but at runtime it's undefined. Your index signature just made a typo invisible!
Problem 2: Everything Becomes Possibly Undefined
The fix? Always union with undefined:
const scores: { [key: string]: number | undefined } = {
math: 95,
science: 88
};
const grade = scores.science; // Type: number | undefined
Now TypeScript forces you to check for undefined everywhere, even for properties you know exist. This is safer but tedious.
The Overly Broad Trap
Think of an index signature like saying "my filing cabinet accepts any label on any drawer." You might only have drawers labeled "A" and "B", but TypeScript will let you open drawer "Z" without warning.
Better Alternatives
Before reaching for index signatures, consider:
- Known properties with optional modifiers:
{ math?: number; science?: number } - The
Recordutility for specific key sets - Mapped types when you know the keys ahead of time
Key Takeaway: Index signatures make all string properties valid, hiding typos and forcing undefined checks everywhere—use them only when you truly need arbitrary keys.