gotchatypescriptnoneMajor
noUncheckedIndexedAccess Catches Missing Array Bounds Checks
Viewed 0 times
TypeScript 4.1+
noUncheckedIndexedAccessarray boundsindex signatureundefined safetyrecord access
Error Messages
Problem
Accessing an array or object index returns type 'T' even if the index is out of bounds, hiding potential undefined values. 'arr[0].name' compiles fine but crashes when arr is empty.
Solution
Enable 'noUncheckedIndexedAccess: true' in tsconfig. Index access now returns 'T | undefined', forcing explicit checks.
// tsconfig.json
{ "compilerOptions": { "noUncheckedIndexedAccess": true } }
const users: User[] = [];
const first = users[0]; // type: User | undefined
// Must handle undefined:
if (first !== undefined) {
console.log(first.name); // OK
}
// Or use optional chaining:
console.log(users[0]?.name);
// Record indexing also affected:
const map: Record<string, number> = {};
const val = map['key']; // number | undefinedWhy
JavaScript array indexing never throws on out-of-bounds access; it returns undefined silently. TypeScript historically typed this as 'T' for convenience, hiding a class of real bugs.
Gotchas
- This flag is NOT included in 'strict: true' — must be opted into separately.
- It breaks a lot of existing code that assumed indexed access is always defined.
- for...of loops are not affected — only bracket notation indexing.
- Tuple types with fixed indices are not affected by this flag.
Revisions (0)
No revisions yet.