TypeScript noUncheckedIndexedAccess: Adopt It in Stages

TypeScript’s noUncheckedIndexedAccess flag adds undefined to the type of every read through an index signature or array index, so names[0] becomes string | undefined and prices[sku] becomes number | undefined. It is not part of strict. On an existing codebase, measure the errors per file first, then ratchet them down in CI before you switch the flag on.

The reason to bother is that the default lies. Without the flag, const first = rows[0] on an empty array gives you undefined at runtime while the type says string, and the crash turns up three calls later as Cannot read properties of undefined (reading 'toUpperCase').

Is noUncheckedIndexedAccess part of strict?

No. It shipped in TypeScript 4.1, and the release notes say it “is not automatically enabled by the strict flag” because it can be noisy. That has not changed. TypeScript 6.0 made strict default to true, and the 6.0 release notes list the defaults that moved; this flag is not among them. TypeScript 7.0.2, the latest tag on npm as of 18 November 2026, behaves the same way.

New projects are different. Since TypeScript 5.9, a plain tsc --init writes "noUncheckedIndexedAccess": true and "exactOptionalPropertyTypes": true into the generated config, under a “Stricter Typechecking Options” comment. We ran tsc --init with 7.0.2 and got both lines. So a team can end up with the flag on in a new service and off in the five-year-old monolith next to it, and code moved between them stops compiling.

What does the flag actually change?

The tsconfig reference puts it in one sentence: it “will add undefined to any un-declared field in the type.” In practice that means every array read by index, arr[i] as much as arr[0], and every array destructuring, so const [first] = names gives string | undefined. It means every lookup on a Record<string, T> or a { [key: string]: T }, whether you write prices.tea or prices["tea"]. Regex capture groups (match[1]) and "a,b".split(",")[0] pick it up too, which is why parsing code tends to collect the most errors.

Some things stay as they were. Tuples with known positions stay exact (pair[0] on [string, number] is string), and so do records with a finite key union like Record<"s" | "m", number>. for...of, forEach and Object.entries() hand you T, not T | undefined. Map.get() and Array.prototype.at() already returned T | undefined, so they produce no new errors.

The errors you will see are TS2532: Object is possibly 'undefined'. and TS18048: 'first' is possibly 'undefined'., with TS2345 where a possibly-undefined value is passed to a parameter that does not accept it.

Why doesn’t a length check narrow the index?

Because TypeScript does not track array length. This still errors with the flag on:

if (names.length > 0) {
  names[0].toUpperCase(); // TS2532
}

So does the classic counting loop, even though the bounds prove the read is safe. Checking the element itself works when the index is a literal or a const:

if (names[0]) names[0].toUpperCase(); // ok

const key = "tea";
if (prices[key]) prices[key].toFixed(); // ok

Indexing with the loop’s let i does not narrow, because i is mutable. Copy the element into a local const and check that instead. We checked every case in this section against TypeScript 5.8.2 and 7.0.2 and got the same errors on the same lines from both.

How do you fix the errors without sprinkling ! everywhere?

Most fixes fall into three patterns. Where you do not need the index, iterate the values and check each lookup in a local. Where a missing value is a real error, throw at runtime with a helper that narrows the type as it goes. Where the loop bounds already prove the read, assert it.

export function must<T>(value: T | undefined, what: string): T {
  if (value === undefined) {
    throw new RangeError(`Missing ${what}`);
  }
  return value;
}

export function parseRange(input: string): [number, number] {
  const match = /^(\d+)-(\d+)$/.exec(input);
  if (!match) throw new SyntaxError(`Bad range: ${input}`);
  const [, from, to] = match; // both string | undefined
  return [Number(must(from, "start")), Number(must(to, "end"))];
}

export function totalFor(
  basket: readonly string[],
  prices: Record<string, number>,
): number {
  let total = 0;
  for (const sku of basket) {
    const price = prices[sku]; // number | undefined
    if (price === undefined) throw new RangeError(`No price for ${sku}`);
    total += price;
  }
  return total;
}

export function deltas(values: readonly number[]): number[] {
  const out: number[] = [];
  for (let i = 1; i < values.length; i++) {
    // The loop bounds prove both reads are in range.
    out.push(values[i]! - values[i - 1]!);
  }
  return out;
}

totalFor is where the flag pays for itself. Without it, a basket containing an unknown SKU quietly returns NaN. With it, the compiler makes you decide what a missing price means.

The non-null assertion in deltas is fine. The 4.1 notes present ! as the explicit “trust me” escape hatch. It is honest when the loop on the line above proves it and a guess everywhere else. A useful review rule: a ! on an index needs the bound check within a few lines, and a ! on a record lookup needs a comment saying why the key must exist.

If a type’s keys really are fixed, fix the type instead. Record<string, number> for a price table with four known SKUs is the wrong type, and a union key (or as const on the object) gets rid of the errors and the bug together.

How do you adopt it on a large codebase?

The flag applies to the whole program, and TypeScript has no per-file switch for it. Splitting tsconfig.json by directory does not help much either, because every file an included file imports is checked under the same settings. That leaves you two options. One is a branch that fixes everything at once. The other is to keep the flag off in tsconfig.json, run it from CI on the command line, and stop the error count from growing.

Start by measuring. This groups the flag’s errors by file and code:

npx tsc --noEmit --pretty false --noUncheckedIndexedAccess \
  | grep -oE '^[^(]+\([0-9]+,[0-9]+\): error TS[0-9]+' \
  | sed -E 's/\([0-9]+,[0-9]+\): error / /' \
  | sort | uniq -c | sort -rn

If the project already compiles cleanly without the flag, every line in that output is caused by it. A few hundred errors spread thinly is an afternoon on a branch. Thousands, or a handful of files with hundreds each (parsers, CSV import code, anything built on split()), means you want the ratchet.

The ratchet records a per-file baseline and fails CI if any file gets worse:

import { execFileSync } from "node:child_process";
import { existsSync, readFileSync, writeFileSync } from "node:fs";

const BASELINE = "nuia-baseline.json";

function countErrors() {
  let output;
  try {
    output = execFileSync(
      "npx",
      ["tsc", "--noEmit", "--pretty", "false", "--noUncheckedIndexedAccess"],
      { encoding: "utf8" },
    );
  } catch (err) {
    if (typeof err.stdout !== "string") throw err;
    output = err.stdout; // tsc exits non-zero when it reports errors
  }
  const counts = {};
  for (const line of output.split("\n")) {
    const match = /^(.+?)\(\d+,\d+\): error TS\d+:/.exec(line);
    if (match) counts[match[1]] = (counts[match[1]] ?? 0) + 1;
  }
  return counts;
}

const current = countErrors();
const total = Object.values(current).reduce((sum, n) => sum + n, 0);

if (process.argv.includes("--update") || !existsSync(BASELINE)) {
  writeFileSync(BASELINE, JSON.stringify(current, null, 2) + "\n");
  console.log(`Baseline written: ${total} errors`);
} else {
  const baseline = JSON.parse(readFileSync(BASELINE, "utf8"));
  let worse = false;
  for (const [file, n] of Object.entries(current)) {
    const allowed = baseline[file] ?? 0;
    if (n > allowed) {
      console.error(`${file}: ${n} errors (baseline ${allowed})`);
      worse = true;
    }
  }
  console.log(`${total} unchecked index errors left`);
  process.exitCode = worse ? 1 : 0;
}

Save it as scripts/nuia-ratchet.mjs, commit the baseline it writes on first run, and add node scripts/nuia-ratchet.mjs as a CI step next to your normal tsc --noEmit. A new file starts with an allowance of zero, so new code is held to the flag from day one. When someone fixes a file, they run it with --update and commit the smaller baseline. When the total reaches zero, set the flag in tsconfig.json, delete the script and the JSON file, and your editor starts showing the errors as you type.

The script counts every error under the flag, so it relies on the normal type-check already being clean. It also starts npx through execFileSync. We ran it on macOS; on a Windows runner npx is a .cmd file, which execFileSync will not start without shell: true.

What we would do

On anything new, keep the flag tsc --init already gave you. On an existing service, run the measuring command this week. Under a few hundred errors, fix them on one branch and turn the flag on. Over that, put the ratchet in CI and fix files when you are already editing them for other reasons. Leave it off where the code is mostly fixed-shape tuples and finite-key records, which the flag barely affects, or where nobody is going to burn the count down. Turning it on and silencing each error with ! gets you the flag’s noise without its checks, because every assertion hides the same undefined read the flag was there to expose.

We saw identical errors from 5.8 and 7.0, so it can go in before or after the compiler upgrade in our TypeScript 7 migration notes. If you use Node’s built-in test runner, the must() and totalFor() cases above are two-line tests worth keeping. Tightening type safety on codebases that have grown without it is a regular part of our TypeScript development work.

Need this built properly?

Get in touch

Hack the planet!