Advertisement
Intermediate TypeScript, Index Signatures & Record Types

Why does TypeScript allow reading a property from an object typed with a string index signature even if that exact key doesn't actually exist at runtime, and how does noUncheckedIndexedAccess change this?

Short answer

By default, TypeScript trusts the index signature's promise and types every access (even to keys that may not exist) as the declared value type, WITHOUT undefined — this is technically unsound.

Save TypeScript mock interview
Advertisement
AModel answer
By default, TypeScript trusts the index signature's promise and types every access (even to keys that may not exist) as the declared value type, WITHOUT undefined — this is technically unsound. Enabling noUncheckedIndexedAccess makes indexed access return `ValueType | undefined` instead, correctly reflecting that the key might not actually be present.
interface Scores { [name: string]: number; }
const scores: Scores = { alice: 90 };
const bobScore = scores.bob; // typed as 'number' by default, but is actually undefined at runtime!

// With noUncheckedIndexedAccess: true
// bobScore would be typed as 'number | undefined' instead
Real-world example
Catching a real class of runtime bugs where code assumes every dynamic lookup succeeds, only to get undefined unexpectedly.
Likely follow-ups
  • Why isn't noUncheckedIndexedAccess enabled by default, given it catches real bugs?
Related topics