Sub topic 11
Missing values at API boundaries: Map, DOM, arrays
This chapter assumes you know union types, how strictNullChecks makes null and undefined part of a type, and how to narrow a value with if checks, ?., and ??. Here you apply those tools to the places where missing values enter a program. The code you write usually doesn't produce them. They come from standard library calls, browser APIs, and data you receive.
Why boundaries matter
Inside your own code you decide whether a value can be missing, and the type says so. At a boundary, a library or the runtime decides. A key might not be in a map. An element might not be on the page. An array might be empty.
TypeScript's standard library declarations describe most of these cases honestly. Map.get returns V | undefined and querySelector returns Element | null. Two cases are not described honestly by default. Plain index access such as items[0] is typed as if the element always exists. Data parsed from JSON has no useful type at all. Most of this chapter is about handling both groups.
Map.get returns undefined
A Map can't know at compile time which keys it holds. So get always includes undefined in its result type.
const scores = new Map<string, number>();
scores.set("ada", 10);
const score = scores.get("ada"); // number | undefined
if (score !== undefined) {
console.log(score + 1);
}Writing score + 1 before the check is an error: 'score' is possibly 'undefined'. The check narrows score to number inside the block.
Calling has() does not narrow get()
A common attempt looks safe but does not compile:
const scores = new Map<string, number>([["ada", 10]]);
if (scores.has("ada")) {
// Error: 'scores.get(...)' is possibly 'undefined'
// console.log(scores.get("ada") + 1);
}The compiler does not link has("ada") to a later get("ada"). The usual fix is to call get once, store the result, and check that. Reaching for scores.get("ada")! here silences the error, but it bypasses the check you are trying to make. The non-null assertion is covered in its own chapter.
Providing a default
When a missing key has a sensible fallback, use ??.
const scores = new Map<string, number>([["ada", 10]]);
const adaScore = scores.get("ada") ?? 0;
const graceScore = scores.get("grace") ?? 0;
console.log(adaScore, graceScore); // 10 0For "get or create" patterns, wrap the logic in one generic helper so the check lives in a single place.
function getOrCreate<K, V>(map: Map<K, V>, key: K, create: () => V): V {
const existing = map.get(key);
if (existing !== undefined) {
return existing;
}
const created = create();
map.set(key, created);
return created;
}
const groups = new Map<string, string[]>();
getOrCreate(groups, "fruit", () => []).push("apple");
getOrCreate(groups, "fruit", () => []).push("pear");
console.log(groups.get("fruit")); // [ 'apple', 'pear' ]The helper treats a stored undefined the same as a missing key. If your map stores undefined as a real value, such as Map<string, number | undefined>, use has() to tell the two cases apart. Avoid that design when you can, because it makes get() ambiguous.
DOM queries return null
The DOM is a second boundary. The page's HTML is not visible to the compiler, so any lookup can come back empty.
const el = document.querySelector("#app"); // Element | null
if (el instanceof HTMLElement) {
el.hidden = false;
}Two things happen in that instanceof check. It removes null, because null instanceof HTMLElement is false. It also narrows from the general Element to HTMLElement, which has properties such as hidden, style, and focus(). A plain if (el) check would remove only the null.
These DOM lookups have different result types:
| Call | Result type | Column |
|---|---|---|
| `document.getElementById("x")` | `HTMLElement \ | null` |
| `document.querySelector("#x")` | `Element \ | null` |
| `document.querySelector("input")` | `HTMLInputElement \ | null` (the tag name selects the type) |
| `document.querySelectorAll("li")` | `NodeListOf<HTMLLIElement>` (never null, may be empty) | |
| `localStorage.getItem("k")` | `string \ | null` |
The generic argument is not a check
You can write document.querySelector<HTMLInputElement>("#name"). The result is HTMLInputElement | null, so the null is still there. The generic argument is also unchecked. If #name is actually a div, the compiler won't notice, and the code fails when it runs. Prefer instanceof when you need a specific element type.
Fail early with a helper
Many scripts need an element to exist and have nothing sensible to do otherwise. A small helper makes that explicit and gives a useful error message.
function requireElement(selector: string): HTMLElement {
const el = document.querySelector(selector);
if (!(el instanceof HTMLElement)) {
throw new Error(`No HTML element matches "${selector}"`);
}
return el;
}
const app = requireElement("#app");
app.hidden = false;Every caller then gets a plain HTMLElement. The decision about what to do when the element is missing is made once, at the boundary.
Arrays: methods that say so, and index access that does not
Array methods that can come up empty declare it in their return type.
const names = ["ada", "grace"];
const found = names.find((n) => n.startsWith("g")); // string | undefined
const last = names.pop(); // string | undefined
const first = names.at(0); // string | undefined
console.log(found?.toUpperCase(), last ?? "none", first ?? "none");at() needs the es2022 library (or newer) in your lib or target setting. indexOf and findIndex don't use undefined at all. They return -1 for "not found", and the compiler does not flag a forgotten -1 check.
Plain indexing is typed as always present
Square-bracket access is different:
const items: string[] = [];
const item = items[0]; // type: string, value: undefined
console.log(item.length); // compiles, then throws TypeError at runtimeWith default settings, items[0] has type string, even on an empty array. The compiler cannot know the length. This is the most common case where strictNullChecks is on and a null-related crash still gets through. The noUncheckedIndexedAccess option, covered in a later chapter, changes it. Until you enable it, handle index access yourself by checking the length, using at(), or annotating the result.
const items: string[] = [];
const viaAt = items.at(0); // string | undefined
const viaAnnotation: string | undefined = items[0];
if (items.length > 0) {
console.log(items[0].toUpperCase()); // fine: you checked the length
}Annotating string | undefined is allowed because string is assignable to string | undefined. This widens the type on purpose, so the compiler makes you handle the missing case.
Filtering missing values out
When an array contains missing values, a type guard removes them and updates the type:
const values: (string | null)[] = ["a", null, "b"];
const present: string[] = values.filter((v): v is string => v !== null);
console.log(present); // [ 'a', 'b' ]Without the v is string predicate, the result is still (string | null)[]. The compiler does not infer the narrowing from the callback's body in older TypeScript versions. TypeScript 5.5 and later can infer a predicate for simple cases like this one. Writing it explicitly works in every version.
Other places where missing values appear
The same pattern shows up in several more APIs:
| Source | Declared type | What to do | Column |
|---|---|---|---|
| `"v1.2".match(/v(\d+)/)` | `RegExpMatchArray \ | null` | Check for null before reading groups |
| `record[key]` where `record: Record<string, number>` | `number` | Declare the value type as `number \ | undefined`, or use a `Map` |
| `JSON.parse(text)` | `any` | Validate the shape, then assign a real type | |
| `process.env.NAME` | `string \ | undefined` | Check at startup and fail early |
| Destructuring `const [a] = list` | `T` | Same hole as index access |
any is the most dangerous entry, because it switches off all checking on whatever it touches. Treat JSON.parse output as unknown data and convert it to a real type in one place.
interface Config {
retries: number;
}
function parseConfig(text: string): Config {
const raw: unknown = JSON.parse(text);
if (
typeof raw === "object" &&
raw !== null &&
"retries" in raw &&
typeof raw.retries === "number"
) {
return { retries: raw.retries };
}
throw new Error("Invalid config");
}
console.log(parseConfig('{"retries": 0}')); // { retries: 3 } is not used; prints { retries: 0 }Note the raw !== null check. typeof null is "object", so without it the in operator would throw on null.
Deciding at the boundary
For each boundary value, pick one of three outcomes and do it once, close to where the value arrives.
The three outcomes behave differently:
- Default: the rest of the code sees a plain type. Use it only when the default is correct and not just convenient.
- Nullable return: the caller is forced to handle absence. This suits lookups where "not found" is a normal result.
- Throw: the rest of the code sees a plain type, and bad input fails loudly at the boundary. This suits required configuration and required page elements.
Avoid the fourth option, which is spreading ! assertions through the code. It pushes the failure from the boundary to some later line.
Common errors
- Using
||for defaults on numbers or strings.map.get(key) || 10replaces a stored0or"". Use??. - Trusting
items[0]on a possibly empty array. Check the length, useat(), or enablenoUncheckedIndexedAccess. - Assuming
has()narrowsget(). It doesn't. Store the result ofget()and check it. - Using a generic argument instead of a check.
querySelector<HTMLCanvasElement>(...)still returnsnulland does not verify the element type. - Forgetting that
findreturnsundefinedwhen a predicate matchesundefinedvalues. If the array can containundefined,findcannot distinguish "no match" from "matched undefined". UsefindIndex.
Exercise
This code compiles under strict settings but can crash at runtime. Explain why, then rewrite it so the compiler reports the problem. const queue: string[] = []; const next = queue[0]; console.log(next.toUpperCase());
Show answer
With default settings, indexing an array gives type string, not string | undefined, so the compiler accepts next.toUpperCase() even though queue is empty and next is undefined at runtime. Rewrite it with an explicit wider type or at(): const next: string | undefined = queue[0]; or const next = queue.at(0); Then next.toUpperCase() is an error ('next' is possibly 'undefined'), and you handle it with next?.toUpperCase() or an if check.
Exercise
Write a function countWord(counts: Map<string, number>, word: string): void that adds one to the count for word, starting from 0 if the word is not in the map. Use only get, set, and ??, and no non-null assertion.
Show answer
function countWord(counts: Map<string, number>, word: string): void { const current = counts.get(word) ?? 0; counts.set(word, current + 1); } counts.get(word) has type number | undefined, and ?? 0 narrows the result to number. Using || would also work for this case because the count 0 is replaced by 0, but ?? states the intent: only a missing key gets the default.