Sub topic 5
Handling Missing Keys with `noUncheckedIndexedAccess`
This chapter assumes basic TypeScript types, interfaces, type aliases, union types, and JavaScript property access. It also assumes you know that an index signature describes an object whose keys are not all known in advance.
An index signature usually promises a value type for every key:
interface Scores {
[name: string]: number;
}
const scores: Scores = {
alice: 90,
};
const score = scores["bob"];Without extra compiler settings, TypeScript treats score as a number. At runtime, however, scores["bob"] is undefined because that key does not exist. This mismatch can cause errors when code uses the result immediately.
Enable `noUncheckedIndexedAccess`
The noUncheckedIndexedAccess compiler option adds undefined to values read through an index signature.
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true
}
}With this option, the previous lookup has type number | undefined:
interface Scores {
[name: string]: number;
}
const scores: Scores = {
alice: 90,
};
const score = scores["bob"]; // number | undefined
if (score !== undefined) {
console.log(score.toFixed(0));
}The check is required before using a number method. This reflects the actual runtime behavior: a dictionary can lack any particular key.
| Expression | Type with the option enabled | Column |
|---|---|---|
| `scores["alice"]` | `number \ | undefined` |
| `scores[userName]` | `number \ | undefined` |
| `scores.toString` | The declared member type, if one exists |
A known property declared separately can remain definite. The option mainly protects accesses whose keys are not known to be present.
Model a lookup as a two-step operation
A dictionary lookup has two separate actions:
- Find the value associated with a key.
- Decide what to do if the value is missing.
A helper function can make this decision explicit:
interface Prices {
[productId: string]: number;
}
function formatPrice(prices: Prices, productId: string): string {
const price = prices[productId];
if (price === undefined) {
return "Price unavailable";
}
return `$${price.toFixed(2)}`;
}
const prices: Prices = {
book: 12.5,
};
console.log(formatPrice(prices, "book")); // $12.50
console.log(formatPrice(prices, "pen")); // Price unavailableDo not silence the error with a non-null assertion unless the key is guaranteed by another part of the program:
const price = prices[productId]!; // Claims the value cannot be undefinedThe ! changes the type checker’s view, but it does not change JavaScript behavior. If the key is absent, the program still receives undefined.
Check whether a key exists
For a plain dictionary whose values cannot legitimately be undefined, checking the value is usually the simplest approach:
const ages: Record<string, number> = {
ann: 30,
};
const age = ages["ann"];
if (age !== undefined) {
console.log(age.toFixed(0));
}When undefined is a valid stored value, distinguish a missing key from an existing key whose value is undefined. Object.hasOwn checks only the object’s own properties:
const settings: Record<string, string | undefined> = {
theme: undefined,
};
if (Object.hasOwn(settings, "theme")) {
console.log("The theme key exists");
}The in operator also finds inherited properties:
const settings: Record<string, string> = {
theme: "dark",
};
console.log("theme" in settings); // true
console.log("toString" in settings); // true
console.log(Object.hasOwn(settings, "toString")); // falseUse Object.hasOwn when the question is “did this dictionary define this key?” Use in when inherited properties should count.
Common patterns
Provide a default when absence is harmless:
const retries: Record<string, number> = {
api: 3,
};
const apiRetries = retries["api"] ?? 0;
const cacheRetries = retries["cache"] ?? 0;
console.log(apiRetries + cacheRetries);The nullish coalescing operator, ??, uses the fallback only for null or undefined. It preserves valid values such as 0.
Exercise
Why does noUncheckedIndexedAccess change ages[name] from number to number | undefined?
Show answer
The compiler cannot prove that an arbitrary string is an existing key, so it includes the value JavaScript returns for a missing property: undefined.