AZ.dev

Make array and record lookups admit they can be undefined

| typescript: 4.1+

Turn on noUncheckedIndexedAccess so indexing an array or a string-keyed record types as T | undefined, which is what it is at runtime.

{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true
  }
}
const users: User[] = [];
const first = users[0];          // User | undefined
const byId: Record<string, User> = {};
const u = byId["missing"];       // User | undefined

Without the flag both are typed User, and users[0].name compiles then throws Cannot read properties of undefined on an empty array.

What changes in existing code

Every index read needs a check or a non-null assertion. The honest patterns:

const first = users[0];
if (!first) return;
first.name;

const last = users.at(-1) ?? fallback;

for (const user of users) user.name;   // iteration was always safe

Loops indexed by i are the noisy case. for...of, .map, and .entries() don’t index, so they need no change.

Gotchas

tsconfig strict noUncheckedIndexedAccess undefined arrays

This entry is one card on a printable cheat sheet:

TypeScript Essentials Cheat Sheet

Was this helpful?

Related Entries

typescript-eslint --fix can break Prisma JSON column writesMake a switch fail to compile when a union case is missingCheck an object against a type without losing its literal types