Accessing Properties with Index Signatures
You'll learn why accessing properties through an index signature can return undefined, even when TypeScript doesn't always force you to check.
The Core Idea
When you use an index signature to define an object type, you're saying "this object can have any number of properties with keys of a certain type." But here's the catch: TypeScript knows that when you access a property using bracket notation, that key might not actually exist in the object at runtime.
type StringMap = {
[key: string]: number;
};
const scores: StringMap = {
alice: 95,
bob: 87
};
const aliceScore = scores["alice"]; // Type: number
const charlieScore = scores["charlie"]; // Type: number (but undefined at runtime!)
Notice something dangerous? TypeScript types both accesses as number, but charlieScore is actually undefined because "charlie" doesn't exist in the object!
The Type System's Weakness
When you access a property through an index signature, TypeScript returns the ValueType from your signature—it doesn't automatically add | undefined. This is a known unsoundness in TypeScript's type system for practical reasons (strict checking would be too noisy).
However, if you've proven a key exists—say, by checking with the in operator first—you can safely access it:
if ("alice" in scores) {
const score = scores["alice"]; // Safe: we checked it exists
}
Key Takeaway: Index signature access always assumes the property exists, returning ValueType instead of ValueType | undefined. Always validate keys exist at runtime before accessing them to avoid undefined surprises.