Why does rows[idx].email type-check and still crash at runtime?
Question
Your tsconfig.json already sets "strict": true. When rows has 1 user and callers pass idx = 2 or id = "u_99", primaryEmail compiles cleanly and crashes in production with TypeError: Cannot read properties of undefined (reading 'email'). Worse, passing id = "toString" returns "[email protected] / undefined" without crashing.
- Why does
"strict": truetyperows[idx]andbyId[id]asUserinstead ofUser | undefined? - Which compiler flag catches both at compile time?
- Fix
primaryEmailusing safe narrowing (Array.prototype.at()andMap.get()), without!assertions.
type User = { id: string; email: string };
function primaryEmail(
rows: User[],
byId: Record<string, User>,
idx: number,
id: string
): string {
return (rows[idx].email + " / " + byId[id].email).toLowerCase();
}Show hints (3)
- "STRICT EXCLUDES INDEXING"
"strict": trueturns onstrictNullChecks, yet TypeScript still assumes array and index-signature lookups succeed unless you enable one extra flag. - "ENABLE THE FLAG"
Set
"noUncheckedIndexedAccess": trueintsconfig.json. Bothrows[idx]andbyId[id]then includeundefinedin their type. - "NARROW SAFELY"
Use
idx >= 0 ? rows.at(idx) : undefinedandbyId.get(id)on aMap<string, User>. Both returnUser | undefined, andMapavoidsObject.prototypekeys like"toString".
Show checked explanation
TypeScript excludes noUncheckedIndexedAccess from "strict": true, so rows[idx] and byId[id] are typed as User even when out of bounds or missing. Enable "noUncheckedIndexedAccess": true, narrow missing lookups with explicit guards, and prefer Map.get() (plus Object.hasOwn() on plain records) over unchecked bracket access.
type User = { id: string; email: string };
function primaryEmail(
rows: readonly User[],
byId: ReadonlyMap<string, User>,
idx: number,
id: string
): string {
const row = idx >= 0 ? rows.at(idx) : undefined;
const found = byId.get(id);
const first = row ? row.email : "missing";
const second = found ? found.email : "missing";
return `${first} / ${second}`.toLowerCase();
}
const users: User[] = [{ id: "u_1", email: "[email protected]" }];
const byId = new Map(users.map((u) => [u.id, u]));
console.log(primaryEmail(users, byId, 0, "u_1"));
console.log(primaryEmail(users, byId, 2, "toString"));[email protected] / [email protected] missing / missing
TypeScript starter crashes and solution output executed on Node.js v24.15.0 (native type-stripping, no tsc type-checker) across out-of-bounds, negative-index, missing-key, and prototype-key cases via Python 3.12.10; compiler flag behavior checked against TypeScript 5 and MDN documentation. Checked by an editor other than the author.
Walkthrough
Even with "strict": true (which enables strictNullChecks), TypeScript assumes index lookups on arrays (User[]) and index signatures (Record<string, User>) always return User. It makes that trade-off so common loops like for (let i = 0; i < rows.length; i++) stay less verbose by default.
The downside is real crashes and silent bugs whenever an index or key comes from URL params, user clicks, or filtered lists.
| Lookup | Default strict: true type | With noUncheckedIndexedAccess: true | Runtime on missing entry |
|---|---|---|---|
rows[2] (len 1) | User | User | undefined | undefined -> TypeError on .email |
byId["u_99"] | User | User | undefined | undefined -> TypeError on .email |
byId["toString"] | User | User | undefined | Object.prototype.toString -> .email is undefined |
map.get("toString") | User | undefined | User | undefined | undefined (safe) |
1. Turn on noUncheckedIndexedAccess. In tsconfig.json, add "noUncheckedIndexedAccess": true. Every bracket lookup on an array or Record<string, T> becomes T | undefined, forcing a guard before reading .email.
2. Prefer Map.get() for dynamic keys. Unlike Record<string, User>, Map.get(id) is always typed User | undefined even without the flag, and it never collides with inherited keys like "toString" or "constructor". If you must keep a plain object, guard with Object.hasOwn(byId, id) (or create it with Object.create(null)).
3. Guard negative indices with .at(). rows.at(idx) is also typed User | undefined by default, yet rows.at(-1) reads the last element! Prefixing idx >= 0 ? rows.at(idx) : undefined prevents negative indices from silently returning the wrong user.
Common mistakes
- Silencing
noUncheckedIndexedAccesswith non-null assertions (rows[idx]!.email). That deletes the safety check and puts the exact sameTypeErrorback. - Assuming
"strict": truealready enablesnoUncheckedIndexedAccess. You must enablenoUncheckedIndexedAccessseparately intsconfig.json. - Using
rows.at(idx)for untrusted indices without checkingidx >= 0. Passing-1silently returns the last element instead ofundefined. - Checking
if (byId[id])on a plainRecord<string, User>. Prototype keys like"toString"are truthy functions, so.emailstill becomesundefined.
Follow-up questions
- "Why does
for (const row of rows)avoidundefinedchecks even withnoUncheckedIndexedAccessenabled?"for...of,.map(), and.filter()iterate only existing elements, sorowhas typeUserdirectly. You only hitUser | undefinedwhen indexing by number (rows[i]), where the compiler cannot proveiis in range. - "If you already checked
if (rows.length > 0), why isrows[0]stillUser | undefined?" TypeScript does not track array length through.length > 0for plain array types (User[]orreadonly User[]). Destructureconst [first] = rows; if (!first) return;or use a non-empty tuple type[User, ...User[]]when at least one element is guaranteed. - "How do you adopt
noUncheckedIndexedAccessin a large existing codebase without breaking hundreds of files at once?" Start by replacing dynamic lookups withMap.get()andfor...of, or enable the flag per package in a monorepo. Fix real missing-key bugs during migration instead of mass-adding!assertions.
What a strong answer covers
Explains why strict: true omits noUncheckedIndexedAccess, enables the flag, narrows safely without !, catches the Array.prototype.at(-1) negative-index trap, and explains why Map.get() or Object.hasOwn() prevents prototype-key bugs.
Open in interactive practice deck →