download

Why does rows[idx].email type-check and still crash at runtime?

Frontend~7 minReviewed 3 Dec 2026Free · No sign-in

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.

  1. Why does "strict": true type rows[idx] and byId[id] as User instead of User | undefined?
  2. Which compiler flag catches both at compile time?
  3. Fix primaryEmail using safe narrowing (Array.prototype.at() and Map.get()), without ! assertions.
"CODE · TYPESCRIPT"
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)
  1. "STRICT EXCLUDES INDEXING"

    "strict": true turns on strictNullChecks, yet TypeScript still assumes array and index-signature lookups succeed unless you enable one extra flag.

  2. "ENABLE THE FLAG"

    Set "noUncheckedIndexedAccess": true in tsconfig.json. Both rows[idx] and byId[id] then include undefined in their type.

  3. "NARROW SAFELY"

    Use idx >= 0 ? rows.at(idx) : undefined and byId.get(id) on a Map<string, User>. Both return User | undefined, and Map avoids Object.prototype keys 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.

"SOLUTION · TYPESCRIPT"
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"));
"OUTPUT"
[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.

LookupDefault strict: true typeWith noUncheckedIndexedAccess: trueRuntime on missing entry
rows[2] (len 1)UserUser | undefinedundefined -> TypeError on .email
byId["u_99"]UserUser | undefinedundefined -> TypeError on .email
byId["toString"]UserUser | undefinedObject.prototype.toString -> .email is undefined
map.get("toString")User | undefinedUser | undefinedundefined (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 noUncheckedIndexedAccess with non-null assertions (rows[idx]!.email). That deletes the safety check and puts the exact same TypeError back.
  • Assuming "strict": true already enables noUncheckedIndexedAccess. You must enable noUncheckedIndexedAccess separately in tsconfig.json.
  • Using rows.at(idx) for untrusted indices without checking idx >= 0. Passing -1 silently returns the last element instead of undefined.
  • Checking if (byId[id]) on a plain Record<string, User>. Prototype keys like "toString" are truthy functions, so .email still becomes undefined.

Follow-up questions

  • "Why does for (const row of rows) avoid undefined checks even with noUncheckedIndexedAccess enabled?" for...of, .map(), and .filter() iterate only existing elements, so row has type User directly. You only hit User | undefined when indexing by number (rows[i]), where the compiler cannot prove i is in range.
  • "If you already checked if (rows.length > 0), why is rows[0] still User | undefined?" TypeScript does not track array length through .length > 0 for plain array types (User[] or readonly User[]). Destructure const [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 noUncheckedIndexedAccess in a large existing codebase without breaking hundreds of files at once?" Start by replacing dynamic lookups with Map.get() and for...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 →

Original OfferVibe question. TSConfig noUncheckedIndexedAccess · Array.prototype.at() (MDN) · Map.prototype.get() (MDN).
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.