noUncheckedIndexedAccess: Array and Object Safety
What you'll learn: How noUncheckedIndexedAccess prevents silent runtime bugs by treating array and object access as potentially undefined.
The Hidden Danger
When you access an array element or object property by index in TypeScript, the compiler normally assumes it exists:
const numbers = [1, 2, 3];
const first = numbers[0]; // Type: number
const tenth = numbers[10]; // Type: number (but actually undefined at runtime!)
This is a lie. numbers[10] doesn't exist, but TypeScript says it's a number. This mismatch causes runtime crashes.
What noUncheckedIndexedAccess Does
When enabled, this flag adds | undefined to every indexed access:
// With noUncheckedIndexedAccess enabled
const numbers = [1, 2, 3];
const first = numbers[0]; // Type: number | undefined
const tenth = numbers[10]; // Type: number | undefined (truthful!)
// Now you must handle the undefined case
if (first !== undefined) {
const doubled = first * 2; // OK: narrowed to number
}
Arrays, Objects, and Index Signatures
This applies to all indexed access patterns:
const obj: { [key: string]: number } = { a: 1 };
const value = obj["b"]; // Type: number | undefined
const tuple: [string, number] = ["hello", 42];
const second = tuple[1]; // Type: number | undefined
The analogy: It's like TypeScript admitting "I don't know if that drawer has anything in it" instead of confidently claiming "there's definitely a sock in drawer 10" when there are only 3 drawers.
When This Helps
This flag catches:
- Out-of-bounds array access
- Missing object keys
- Loop iteration bugs
- Incorrect length assumptions
The Trade-off
You'll write more null checks, but you'll catch real bugs. Even [0] on a known array becomes | undefined, which can feel strict—but arrays can be empty.
Key Takeaway: noUncheckedIndexedAccess makes TypeScript honest about indexed access, forcing you to handle the reality that arrays and objects might not contain what you expect at any given index.