noUncheckedIndexedAccess: Safer Array and Object Indexing
What you'll learn: How to force TypeScript to treat array and object index access as potentially undefined, preventing a common category of runtime errors.
The Hidden Danger of Index Access
By default, TypeScript assumes that accessing an array element or object property via an index always succeeds:
const users = ["Alice", "Bob"];
const third = users[2]; // Type: string (not string | undefined!)
TypeScript types third as string, even though users[2] is actually undefined at runtime. This is an unsound assumption that can lead to crashes when you call methods on non-existent elements.
How noUncheckedIndexedAccess Changes Behavior
When you enable noUncheckedIndexedAccess in your tsconfig.json:
{
"compilerOptions": {
"noUncheckedIndexedAccess": true
}
}
TypeScript now treats all indexed access (arrays and objects with index signatures) as potentially undefined:
const users = ["Alice", "Bob"];
const third = users[2]; // Type: string | undefined
// Now TypeScript forces you to handle the undefined case:
third.toUpperCase(); // Error: Object is possibly 'undefined'
// You must narrow first:
if (third !== undefined) {
third.toUpperCase(); // OK
}
Impact on Objects with Index Signatures
This flag also affects objects with index signatures:
const scores: { [key: string]: number } = { Alice: 95 };
const bobScore = scores["Bob"]; // Type: number | undefined (not just number)
const doubled = bobScore * 2; // Error: Object is possibly 'undefined'
When to Enable This Flag
This option is not included in strict, so you must opt in explicitly. It's recommended when:
- You frequently access arrays at dynamic indices
- You work with object lookups where keys might not exist
- You want maximum safety around collection access
The trade-off is more verbose code requiring null checks, but it catches real bugs that TypeScript's default behavior misses.
Key Takeaway: noUncheckedIndexedAccess makes TypeScript treat indexed array and object access as potentially undefined, preventing unchecked element access bugs at the cost of requiring explicit undefined handling.