Sub topic 11
Missing values at API boundaries: Map, DOM, arrays
Assume strictNullChecks is enabled and you already know TypeScript types, unions, interfaces, and basic tsconfig.json settings. At an API boundary, a value may be missing even when the value you want has a useful type. TypeScript makes that possibility visible so you handle it before using the value.
`Map.get` can return `undefined`
A Map<K, V> stores values by key. Calling get returns V | undefined, because the key might not exist.
const scores = new Map<string, number>();
scores.set("ada", 10);
const score = scores.get("ada"); // number | undefined
if (score !== undefined) {
console.log(`${score} points`);
}The check narrows score from number | undefined to number. You can then use it safely.
A default value is useful when a missing key should have a normal fallback:
function scoreFor(scores: Map<string, number>, name: string): number {
return scores.get(name) ?? 0;
}
console.log(scoreFor(scores, "grace")); // 0Use has when you need to distinguish a missing key from a stored value. For example, a map can contain a key whose value is undefined, so has and get answer different questions.
const settings = new Map<string, string | undefined>();
settings.set("theme", undefined);
console.log(settings.has("theme")); // true
console.log(settings.get("theme")); // undefinedDOM queries can return `null`
Browser DOM methods use null when no matching element exists. A query also often returns a broad element type.
const element = document.querySelector("#app"); // Element | null
if (element instanceof HTMLElement) {
element.hidden = false;
}The instanceof check performs two jobs:
- It proves that
elementis notnull. - It narrows the type from
ElementtoHTMLElement, which has thehiddenproperty.
You can use a more specific query when you know the element type:
const input = document.querySelector<HTMLInputElement>("#email");
if (input !== null) {
console.log(input.value);
}The type argument improves the element type, but it does not prove that the element exists. You still need the null check.
Optional chaining is convenient when no element is acceptable:
document.querySelector<HTMLInputElement>("#email")?.focus();The focus call runs only when the query returns an element.
Array indexing may produce `undefined`
Without extra compiler settings, TypeScript usually treats an indexed access such as items[0] as the element type, even though the index can be outside the array.
const colors = ["red", "green"];
const first = colors[0]; // string
console.log(first.toUpperCase());This code is safe for index 0 when the array is known to contain an element. An arbitrary index is less certain at runtime:
function colorAt(colors: string[], index: number): string {
return colors[index] ?? "unknown";
}The ?? fallback handles an out-of-range index. It does not replace an empty string, because an empty string is not null or undefined.
Enabling noUncheckedIndexedAccess makes indexed access safer:
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true
}
}With this option, colors[index] has type string | undefined. Existing code may produce new errors, but those errors identify places where an index needs validation.
A boundary-handling pattern
Handle missing values as soon as they enter your function. Then keep the rest of the function working with a definite value.
function labelFor(
labels: Map<string, string>,
id: string
): string {
const label = labels.get(id);
if (label === undefined) {
return "Unnamed";
}
return label.toUpperCase();
}This pattern keeps uncertainty at the boundary instead of spreading undefined checks through later code.
Exercise
What type should a function return if it calls names.get(id) and returns the stored name, or "unknown" when the key is missing?
Show answer
It should return string. Use return names.get(id) ?? "unknown"; because the fallback removes undefined.