The boring TS flag that prevents 2am crashes

TypeScriptConfigReliability

There is a tiny switch in your tsconfig.json that most teams ignore. It doesn't add new features. It doesn't make your code run faster. It just quietly forces you to admit that arrays can be empty.


The default lie

By default, TypeScript is an optimist. If you access an array index, it assumes something is definitely there:

const users: User[] = [];

// TypeScript says this is fine:
const user = users[0];
// Type: User

console.log(user.name);
// Runtime: "Cannot read property 'name' of undefined"

This is a lie. Arrays can be empty. Indexes can be out of bounds. But the compiler lets us pretend otherwise — right up until production crashes at 2:37am.


The boring fix

Enable noUncheckedIndexedAccess in your compiler options:

// tsconfig.json
{
  "compilerOptions": {
    "noUncheckedIndexedAccess": true
  }
}

Suddenly, TypeScript stops lying to you:

const user = users[0];
// Type: User | undefined

// Error: Object is possibly 'undefined'
console.log(user.name);

// Forced fix:
if (user) {
  console.log(user.name); // Safe!
}

This flag applies the same strict logic to:

  • Array access: arr[i]
  • Object access: record[key]
  • Dynamic properties: obj[prop]

Warning: it will be annoying at first

When you first turn this on, your build will probably break in a bunch of places. That is good. Every red squiggly is a potential runtime crash that you're moving into compile time. You are trading 2am pager duty for daytime annoyance. That is the definition of boring reliability.

When should you enable it?

  • You're already running with strict or close to it.
  • You're tired of Cannot read X of undefined in logs.
  • You want new code to be safer, even if it means cleaning up some old assumptions.

It's one of those flags you turn on once, fix the fallout, and then forget about — until you notice that your undefined crashes are quietly gone.