Sub topic 5
Handling missing keys with noUncheckedIndexedAccess
This chapter assumes you know basic TypeScript types, interfaces, and type aliases. It also assumes you can read JavaScript objects with dot and bracket notation, and that you understand union types with undefined. You should have seen an index signature such as { [name: string]: number }.
The hole in plain index signatures
An index signature promises that every string key maps to a value of one type. That promise is false for keys nobody has set. Here is a word counter that compiles with default settings and fails at runtime:
const counts: Record<string, number> = {};
for (const word of ["a", "b", "a"]) {
counts[word] = counts[word] + 1; // compiles, but counts["a"] starts as undefined
}
console.log(counts); // { a: NaN, b: NaN }TypeScript reads counts[word] as number. At runtime the first read returns undefined, and undefined + 1 is NaN. The type system is wrong here because the type says "every string key has a number", and the object only holds the keys you actually assigned.
The compiler option noUncheckedIndexedAccess closes this hole. It changes what a read through an index signature returns, so the compiler makes you handle the missing case.
Enabling the option
Add it to compilerOptions in tsconfig.json:
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true
}
}The option is not part of strict. You must turn it on yourself, and it has no effect unless you do. It works best together with strictNullChecks, which strict enables. Without strictNullChecks, undefined is absorbed into every type and the option has nothing visible to add.
What changes
With the option on, any read through an index signature has type T | undefined instead of T. The same rule applies to arrays and to other types with numeric index signatures.
const ages: Record<string, number> = { ann: 30 };
const age = ages["ann"]; // number | undefined
const alsoAge = ages.ann; // number | undefined (dot access on an index signature is also affected)
const list: string[] = ["x", "y"];
const first = list[0]; // string | undefinedThe example above is the same whether you read a key you know exists or one you never set. The compiler cannot tell the difference, because the index signature does not list keys.
The rule applies to reads only. Writes keep the declared value type:
const scores: Record<string, number> = {};
scores["alice"] = 90; // fine, the assigned value must still be number
// scores["bob"] = undefined; // Error: Type 'undefined' is not assignable to type 'number'.Some reads are not affected, because the compiler knows the key exists:
- Properties declared by name, such as
nameininterface Config { [key: string]: string | number; name: string }. Readingconfig.namegivesstring. - Tuple elements at known positions, such as
pair[0]for[string, number]. - Iteration with
for...of,forEach,map, and similar methods, because they only visit elements that exist. - Mapped types over literal unions, such as
Record<"low" | "high", number>, where the keys are fixed.
interface Config {
[key: string]: string | number;
name: string;
retries: number;
}
declare const config: Config;
const n = config.name; // string, because `name` is declared
const other = config["timeout"]; // string | number | undefined, because it is read through the index signatureFour ways to handle `undefined`
Once reads return T | undefined, you must decide what a missing key means. Pick the approach that matches that meaning.
1. Narrow with a check
Use this when the code path only makes sense if the key is present.
const ages: Record<string, number> = { ann: 30 };
const age = ages["ann"];
if (age !== undefined) {
console.log(age.toFixed(0)); // age is number here
} else {
console.log("no age recorded");
}Copying the value into a local variable first is the most reliable pattern. TypeScript narrows a variable everywhere. It narrows ages["ann"] only in some cases. Narrowing an element access works when the key is a literal such as "ann". It also works when the key is a const variable, but only in TypeScript 5.5 and later, and only when the object is not reassigned. If the key is a non-constant string variable, narrowing the access expression does not work:
function printAge(ages: Record<string, number>, name: string): void {
if (ages[name] !== undefined) {
// On older compilers, ages[name] may still be number | undefined here.
}
const age = ages[name]; // always works
if (age !== undefined) {
console.log(age.toFixed(0));
}
}2. Provide a default
Use this when a missing key has a sensible fallback. The ?? operator replaces only undefined and null, so a stored 0 is kept.
const counts: Record<string, number> = {};
for (const word of ["a", "b", "a"]) {
counts[word] = (counts[word] ?? 0) + 1;
}
console.log(counts); // { a: 2, b: 1 }This fixes the counter from the start of the chapter. Do not use || here. It also replaces 0, "", and false, which can be real stored values.
3. Fail loudly
Use this when a missing key is a bug. A small helper keeps the check in one place and returns the plain value type.
function getOrThrow<T>(dict: Record<string, T>, key: string): T {
const value = dict[key];
if (value === undefined) {
throw new Error(`Missing key: ${key}`);
}
return value;
}
const prices: Record<string, number> = { apple: 1.2 };
console.log(getOrThrow(prices, "apple")); // 1.2
// getOrThrow(prices, "pear"); // throws Error: Missing key: pear4. Assert with `!`
The non-null assertion dict[key]! removes undefined from the type without any runtime check. It is correct when you have just proven the key exists in a way the compiler cannot see. If you are wrong, the program fails later and farther from the cause.
const stock: Record<string, number> = { apple: 3 };
if (Object.hasOwn(stock, "apple")) {
const n = stock["apple"]!; // number; we checked above, but the compiler does not know it
console.log(n + 1); // 4
}Object.hasOwn needs the es2022 library or later in your lib setting. Prefer options 1 to 3. They produce the same result without the assertion, and they keep working if the surrounding code changes.
The next diagram summarizes the choice.
A check on the key does not narrow the value
A common mistake is to check that a key exists and expect the value type to improve. Under noUncheckedIndexedAccess, it does not:
const lookup: Record<string, number> = { a: 1 };
const key: string = "a";
if (key in lookup) {
const v = lookup[key]; // still number | undefined
console.log(v);
}
if (Object.hasOwn(lookup, key)) {
const v = lookup[key]; // still number | undefined
console.log(v);
}Both in and Object.hasOwn answer a question about keys. Neither tells the compiler anything about the type of lookup[key]. The reliable form checks the value itself:
const value = lookup[key];
if (value !== undefined) {
console.log(value.toFixed(1));
}There is one caveat for this pattern. If your dictionary can legitimately hold undefined as a value, value !== undefined cannot tell "key missing" from "key present with value undefined". In that case, declare the value type honestly, and use Object.hasOwn for presence:
const optionalNotes: Record<string, string | undefined> = { draft: undefined };
console.log(optionalNotes["draft"]); // undefined
console.log(Object.hasOwn(optionalNotes, "draft")); // true
console.log(Object.hasOwn(optionalNotes, "final")); // falsePrototype pitfalls, such as "toString" in lookup returning true, are covered in the chapter on inherited keys. Here it is enough to know that a value check on a plain object can also be fooled by inherited properties, so do not rely on it for untrusted keys.
Arrays and the same option
The option affects every array[i] read. This is the most disruptive change when you switch it on in an existing project, because arrays are everywhere.
const names: string[] = ["ann", "bob"];
for (let i = 0; i < names.length; i++) {
const name = names[i]; // string | undefined
if (name !== undefined) {
console.log(name.toUpperCase());
}
}
// Iteration avoids the problem entirely:
for (const name of names) {
console.log(name.toUpperCase()); // string
}Prefer for...of, map, and forEach when you need every element. Use an indexed read only when you need a specific position, and handle the undefined result there.
Adopting the option in an existing project
Turning the option on in a large codebase produces many errors at once. A workable plan:
- Enable it in a branch and read the error list. Most errors fall into the same few patterns.
- Fix loops first by replacing index loops with
for...ofwhere the index is not needed. - Fix counters and caches with
??. - Fix lookups that must succeed by adding a
getOrThrow-style helper, instead of scattering!through the code. - Review remaining
!assertions. Each one is a place where the compiler trusts you.
The error count is a measure of how many unchecked reads the code had. Each error marks a place where a missing key could have produced undefined at runtime without any warning.
Limits of the option
- It cannot know which keys exist. Even
const d: Record<string, number> = { a: 1 }; d["a"]isnumber | undefined, because the declared type is what counts, not the initializer. If you know the keys, give the object a type with named properties, or aRecordover a union of literal keys. - It applies to reads only. Nothing stops you from writing a key and then reading a different one by mistake.
- It does not change runtime behavior. It only changes what the compiler accepts.
- It does not affect
Map.Map.getalways returnsT | undefined, with or without the option, soMapalready forces the check. The chapter on Map covers this.
Summary
With noUncheckedIndexedAccess on, reads through index signatures and array indexes have type T | undefined, and writes keep type T. You handle each read by narrowing, supplying a default with ??, throwing in a helper, or, rarely, asserting with !. Key checks with in or Object.hasOwn do not narrow the value type, so check the value itself.
Exercise
The function below is written for a project with noUncheckedIndexedAccess enabled. It fails to compile. Explain why, and rewrite it so it compiles and returns 0 for unknown names. function total(prices: Record<string, number>, name: string, qty: number): number { return prices[name] * qty; }
Show answer
prices[name] has type number | undefined under the option, and multiplying undefined is not allowed. A fix that returns 0 for unknown names: function total(prices: Record<string, number>, name: string, qty: number): number { const price = prices[name]; if (price === undefined) { return 0; } return price qty; } Using (prices[name] ?? 0) qty is also correct and shorter.
Exercise
A teammate writes if (Object.hasOwn(stock, key)) { return stock[key] + 1; } and expects it to compile under noUncheckedIndexedAccess. Does it? Why or why not, and what is a safe alternative?
Show answer
It does not compile. Object.hasOwn checks a key but does not narrow the type of stock[key], which stays number | undefined. A safe alternative is to read the value into a local and check it: const n = stock[key]; if (n !== undefined) { return n + 1; }. If the dictionary values can be undefined, keep Object.hasOwn for the presence test and handle the undefined case explicitly.