Sub topic 9
Possibly undefined: narrowing the value
This chapter assumes you can run tsc, read a diagnostic's file, line, column and code, and know what a union type such as string | undefined is. It covers the family of errors that say a value "is possibly undefined" or "is possibly null", and the ways to resolve them.
Why the compiler complains
With strictNullChecks on (part of strict), undefined and null are not members of every type. A function such as Array.prototype.find returns T | undefined. Using that result as if it were a plain T is unsafe, and the compiler stops you.
const names: string[] = ["ada", "alan"];
const first = names.find((n) => n.startsWith("a"));
console.log(first.length);src/index.ts(4,13): error TS18048: 'first' is possibly 'undefined'.The message names the expression (first) and the missing case (undefined). Related codes differ only in which case is possible:
| Code | Message starts with | Meaning |
|---|---|---|
| TS18048 | `'x' is possibly 'undefined'` | `undefined` is in the union |
| TS18047 | `'x' is possibly 'null'` | `null` is in the union |
| TS18049 | `'x' is possibly 'null' or 'undefined'` | both are in the union |
| TS2722 | `Cannot invoke an object which is possibly 'undefined'` | you called an optional function |
| TS2532 | `Object is possibly 'undefined'` | older wording of the same check |
The same root cause also appears as an assignment or call mismatch. Passing string | undefined to a string parameter gives TS2345, and the chain ends with Type 'undefined' is not assignable to type 'string'. The fixes are identical.
Narrowing
Narrowing means the compiler uses a check in your code to work out a more specific type for a value inside a region of code. After first !== undefined, the type of first inside the if block is string.
const names: string[] = ["ada", "alan"];
const first = names.find((n) => n.startsWith("a"));
if (first !== undefined) {
console.log(first.length);
} else {
console.log("no match");
}The compiler follows control flow. It tracks which branch you are in and removes the impossible members from the union.
Choosing a narrowing tool
Each tool below removes undefined from the type in a different way.
| Tool | Example | Use it when | Watch out for |
|---|---|---|---|
| Explicit comparison | `x !== undefined` | You need to keep valid falsy values | Does not remove `null` unless you use `!= null` |
| Truthiness | `if (x)` | The value is an object or non-empty string | Also rejects `0`, `""`, `false`, `NaN` |
| Early return or throw | `if (x === undefined) return;` | The rest of the function needs the value | None; this is usually the clearest form |
| Optional chaining | `x?.y` | You want `undefined` to flow through | The result type includes `undefined` |
| Nullish coalescing | `x ?? "default"` | A default is correct | Only replaces `null` and `undefined` |
| `typeof` / `in` | `typeof x === "string"` | The union has several member types | `typeof null` is `"object"` |
| Non-null assertion | `x!` | You can prove it, and cannot show it to the compiler | No runtime check at all |
Early exit
Guard clauses keep the main path flat. After the if, the compiler knows s is a string.
function shout(s: string | undefined): string {
if (s === undefined) {
return "";
}
return s.toUpperCase();
}Optional chaining and defaults
?. stops evaluation and yields undefined when the left side is null or undefined. ?? supplies a fallback.
interface Profile {
name: string;
address?: { city: string };
}
function city(p: Profile): string {
return p.address?.city ?? "unknown";
}
console.log(city({ name: "Ada" }));
console.log(city({ name: "Alan", address: { city: "London" } }));Here p.address?.city has type string | undefined. The ?? removes undefined, so the function's return type is satisfied.
The truthiness trap
Truthiness checks compile cleanly but can change behavior. This function treats a count of zero as missing.
function label(count: number | undefined): string {
if (count) {
return `${count} items`;
}
return "no count";
}
console.log(label(0));label(0) prints no count, which is wrong. The compiler accepted it because narrowing by truthiness is valid, only not what you meant. Compare against undefined instead:
function label(count: number | undefined): string {
if (count !== undefined) {
return `${count} items`;
}
return "no count";
}
console.log(label(0));When narrowing disappears
A narrowing is only valid while the compiler can be sure the value has not changed. Two cases surprise people.
Property narrowing inside callbacks
A callback may run later, after other code has changed the object. The compiler therefore discards narrowing of box.value inside the function expression.
interface Box {
value?: string;
}
function printLength(box: Box): void {
if (box.value === undefined) {
return;
}
[1, 2].forEach(() => {
console.log(box.value.length);
});
}The error is TS18048: 'box.value' is possibly 'undefined'. Copy the property into a const. A const cannot be reassigned, so its narrowing survives into the callback.
interface Box {
value?: string;
}
function printLength(box: Box): void {
const value = box.value;
if (value === undefined) {
return;
}
[1, 2].forEach(() => {
console.log(value.length);
});
}Calls between the check and the use
Narrowing of a property such as box.value is not invalidated by a function call in between, even if that call could change it. Narrowing is a local, optimistic analysis. Do not read a passing check as proof that nothing else can change the value.
Lookups that return `undefined`
Several common APIs return a union with undefined:
Map.prototype.getreturnsV | undefined.Array.prototype.findreturnsT | undefined.- Indexing a
Record<string, T>returnsT, unlessnoUncheckedIndexedAccessis enabled. document.getElementByIdreturnsHTMLElement | null.
The noUncheckedIndexedAccess option adds undefined to every index access on arrays and index signatures. It catches real out-of-range bugs but makes ordinary loops noisier.
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": true,
"noUncheckedIndexedAccess": true,
"noEmit": true
},
"include": ["src"]
}With it on, xs[0].length on a string[] reports 'xs[0]' is possibly 'undefined'. The usual fix is a check, or xs.at(0) ?? "" when a default is fine.
Filtering out undefined from arrays
filter(Boolean) does not change the element type in older TypeScript. Write a type predicate, which tells the compiler that a true result means the value has the stated type.
const raw: (string | undefined)[] = ["a", undefined, "b"];
const present: string[] = raw.filter((x): x is string => x !== undefined);
console.log(present.map((s) => s.toUpperCase()));TypeScript 5.5 and later infers this predicate for simple arrow functions like x => x !== undefined. A predicate you write yourself is not checked for correctness, so a wrong one is a lie to the compiler.
When you know better: assertions
first!.length removes undefined from the type without any runtime check. If you are wrong, the program throws TypeError: Cannot read properties of undefined. Where you truly cannot restructure the code, fail loudly with a helper that does check:
function must<T>(value: T | null | undefined, message: string): T {
if (value === null || value === undefined) {
throw new Error(message);
}
return value;
}
const names: string[] = ["ada", "alan"];
const first = must(
names.find((n) => n.startsWith("a")),
"expected a name starting with a",
);
console.log(first.length);This keeps the assumption visible and turns a silent failure into a clear error message.
Common mistakes
- Wrapping the whole function body in
if (x)when an early return would be flatter. - Using
||for defaults, which replaces0and"". Use??. - Changing the declared type to
anyto silence the error, which removes every other check on that value. - Making a parameter optional with
?when the caller always supplies it, which pushes the problem onto every use inside the function.
Exercise
This function fails with TS18048 at user.email.toLowerCase(). Rewrite it so it compiles, returns "none" when there is no email, and still returns "" for a user whose email is an empty string.
interface User { email?: string }
function normalize(user: User): string {
return user.email.toLowerCase();
}
Show answer
Compare with undefined rather than testing truthiness, so an empty string is kept:
function normalize(user: User): string {
if (user.email === undefined) {
return "none";
}
return user.email.toLowerCase();
}
An empty email passes the check and returns "". Writing if (!user.email) would return "none" for it, which changes the behavior.
Exercise
In the code below, settings.timeout is checked before the callback, yet the compiler still reports 'settings.timeout' is possibly 'undefined' inside it. Explain why, and give a fix.
interface Settings { timeout?: number }
function schedule(settings: Settings): void {
if (settings.timeout === undefined) return;
setTimeout(() => console.log(settings.timeout + 1), 10);
}
Show answer
The callback runs later, and the compiler cannot guarantee that settings.timeout was not changed in the meantime, so it discards the property narrowing inside the function. Copy the value into a const after narrowing, because a const keeps its narrowed type in closures: function schedule(settings: Settings): void { const timeout = settings.timeout; if (timeout === undefined) return; setTimeout(() => console.log(timeout + 1), 10); }