Sub topic 3
Reading Optional Values: Narrowing, ?. and ??
An optional property can be missing, so TypeScript will not let you use it as if it were always there. This chapter covers the three tools for reading such a value safely: narrowing with checks, optional chaining (?.), and nullish coalescing (??). It also covers the mistakes that come up most often.
I assume you know basic TypeScript syntax, interfaces, and union types that include undefined. I also assume you have read the previous chapter on declaring optional properties with ?.
What the compiler gives you
Start with the type you get when you read an optional property.
interface User {
id: number;
name: string;
email?: string;
}
function shout(user: User): string {
// return user.email.toUpperCase();
// Error: 'user.email' is possibly 'undefined'.
return user.name.toUpperCase();
}Reading user.email gives the type string | undefined. Calling a string method on that union is an error, because undefined has no toUpperCase. This is the compiler doing its job. Most runtime crashes of the form "Cannot read properties of undefined" come from this situation.
This requires strictNullChecks, which is part of "strict": true. Without it, undefined is silently allowed in every type and the error above never appears. Keep strict on for everything in this chapter.
You have three ways to turn string | undefined into something usable:
- Check first, so the compiler narrows the type.
- Use
?.to stop safely when a value is missing. - Use
??to supply a default.
Narrowing with a check
Narrowing means the compiler tracks your checks and uses a more specific type inside the checked branch. The most direct check compares against undefined.
interface User {
id: number;
name: string;
email?: string;
}
function send(user: User): void {
if (user.email !== undefined) {
console.log(user.email.toUpperCase()); // narrowed to string
} else {
console.log("no email on file");
}
}
send({ id: 1, name: "Ada" });
send({ id: 2, name: "Grace", email: "[email protected]" });Inside the if, user.email is string. The compiler can narrow a property access like user.email because it treats it as a reference it can track until something might change it.
An early return keeps the main path flat:
interface User {
id: number;
name: string;
email?: string;
}
function domain(user: User): string {
if (user.email === undefined) {
return "unknown";
}
return user.email.split("@")[1] ?? "unknown";
}
console.log(domain({ id: 1, name: "Ada", email: "[email protected]" }));After the return, the compiler knows user.email is string for the rest of the function.
Truthiness checks are a trap
You can also write if (user.email). It narrows, but it removes more than undefined. A truthiness check also rejects "", 0, false, and NaN, which are valid values.
interface Item {
name: string;
quantity?: number;
}
function describe(item: Item): string {
if (item.quantity) {
return `${item.name} x${item.quantity}`;
}
return `${item.name} (quantity unknown)`;
}
console.log(describe({ name: "pen", quantity: 0 })); // "pen (quantity unknown)" - wrongA quantity of 0 is a real value, but the check treats it as missing. Use !== undefined when the property can hold falsy values. Use truthiness only when every falsy value really means "nothing here", such as an optional label where an empty string is as good as missing.
Narrowing with `in` and `typeof`
The in operator checks whether a key exists on the object:
interface User {
id: number;
name: string;
email?: string;
}
function hasEmailKey(user: User): boolean {
return "email" in user;
}For an optional property, "email" in user does not guarantee that the value is a string. Without exactOptionalPropertyTypes, the key can exist with the value undefined. Prefer an explicit !== undefined check when you plan to use the value. Reserve in for telling apart members of a union of object types.
A typeof check such as typeof user.email === "string" also works, and it is useful when the property type is a wider union like string | number | undefined.
Optional chaining: `?.`
Optional chaining stops evaluating when the value on its left is null or undefined, and the whole expression becomes undefined.
interface Address {
city: string;
postcode?: string;
}
interface Customer {
name: string;
address?: Address;
tags?: string[];
notify?: (message: string) => void;
}
function inspect(c: Customer): void {
const city = c.address?.city; // string | undefined
const post = c.address?.postcode?.trim(); // string | undefined
const firstTag = c.tags?.[0]; // string | undefined
c.notify?.("hello"); // calls only if notify exists
console.log(city, post, firstTag);
}
inspect({ name: "Ada" });
inspect({
name: "Grace",
address: { city: "Arlington", postcode: " 22201 " },
tags: ["vip"],
notify: (m) => console.log(m),
});There are three forms: a?.b for properties, a?.[i] for index access, and a?.() for calls.
Two details matter in practice.
- Short-circuiting covers the whole chain. In
c.address?.postcode?.trim().length, ifc.addressis missing, the engine skips everything to the right, including.trim().length. You only need?.at each point where a value might be missing, not after every dot. - The result type always includes
undefined.c.address?.cityisstring | undefined, even thoughcityitself is required onAddress. Theundefinedcomes from the possibility thataddressis missing.
Optional chaining reads values. You cannot use it on the left side of an assignment, so c.address?.city = "x" is a syntax error. Narrow with an if before writing.
Nullish coalescing: `??`
The ?? operator returns its right side only when the left side is null or undefined.
interface Options {
retries?: number;
label?: string;
}
function resolve(o: Options): { retries: number; label: string } {
return {
retries: o.retries ?? 3,
label: o.label ?? "default",
};
}
console.log(resolve({})); // { retries: 3, label: "default" }
console.log(resolve({ retries: 0, label: "" })); // { retries: 0, label: "" }The second call is the point. With ??, 0 and "" are kept, because they are not nullish.
`??` versus `||`
The older idiom value || fallback replaces every falsy value, not just missing ones.
| Left value | `x ?? "fallback"` | `x \ | \ | "fallback"` |
|---|---|---|---|---|
| `undefined` | `"fallback"` | `"fallback"` | ||
| `null` | `"fallback"` | `"fallback"` | ||
| `""` | `""` | `"fallback"` | ||
| `0` | `0` | `"fallback"` | ||
| `false` | `false` | `"fallback"` |
For optional properties, ?? is almost always what you mean. Use || only when you deliberately want to treat empty strings and zero as missing.
Assigning a default: `??=`
The logical assignment form ??= assigns only when the current value is nullish:
interface Options {
retries?: number;
}
function withDefaults(o: Options): Options {
o.retries ??= 3;
return o;
}
console.log(withDefaults({})); // { retries: 3 }
console.log(withDefaults({ retries: 0 })); // { retries: 0 }This mutates the object. If the object is readonly, which later chapters cover, build a new one instead.
Combining the tools
Chaining and coalescing are usually used together. ?. produces undefined when something is missing, and ?? replaces it:
interface User {
id: number;
name: string;
email?: string;
}
function contact(user: User): string {
return user.email?.toLowerCase() ?? "no email on file";
}
console.log(contact({ id: 1, name: "Ada" }));
console.log(contact({ id: 2, name: "Grace", email: "[email protected]" }));The expression is string | undefined before ?? and plain string after it. When the fallback is the same type as the value, the result type has no undefined.
The following diagram shows how the compiler and runtime treat a read of an optional property.
Common errors
Narrowing lost inside callbacks
The compiler does not keep a narrowing of a property such as user.email inside a function created later, because the property could change before the function runs.
interface User {
id: number;
name: string;
email?: string;
}
function makeShouter(user: User): () => string {
if (user.email === undefined) {
return () => "none";
}
// return () => user.email.toUpperCase();
// Error: 'user.email' is possibly 'undefined' (narrowing is not kept in the closure).
const email = user.email; // copy the narrowed value into a const
return () => email.toUpperCase();
}
console.log(makeShouter({ id: 1, name: "Ada", email: "[email protected]" })());Copy the value to a const after narrowing, and use the copy inside the callback. A const of type string cannot become undefined later.
Reaching for the non-null assertion
The postfix ! tells the compiler to trust you:
interface User {
id: number;
name: string;
email?: string;
}
function risky(user: User): string {
return user.email!.toUpperCase(); // compiles, throws at runtime if email is missing
}The ! is erased at compile time and adds no runtime check. If the property is missing, you get the same crash TypeScript was warning you about. Use it only when you can point to a guarantee the type system cannot see, and prefer a check or ?? otherwise.
Over-using `?.` on values that cannot be missing
Writing user.name?.toUpperCase() when name is required compiles, but it hides the type's intent and returns string | undefined for no reason. Add ?. only where the type includes undefined or null. Linters can flag unnecessary optional chains.
Treating a missing property and `undefined` as different
Without exactOptionalPropertyTypes, {} and { email: undefined } both satisfy email?: string. Your reading code cannot tell them apart, and it should not try. ?., ??, and !== undefined all treat the two cases the same way.
Exercises
Exercise
Given interface Item { name: string; quantity?: number }, a function returns item.quantity || 1. What does it return for { name: "pen", quantity: 0 }, and what single operator change fixes the bug?
Show answer
It returns 1, because 0 is falsy and || replaces it. Changing || to ?? returns 0, because ?? only replaces null and undefined.
Exercise
Why does this code fail to compile, and how do you fix it without using !?
function make(user: { email?: string }): () => number {
if (user.email === undefined) return () => 0;
return () => user.email.length;
}
Show answer
The narrowing of user.email is not kept inside the arrow function, so the property is string | undefined there. Copy the narrowed value into a constant, for example const email = user.email;, and return () => email.length.
Exercise
What is the type of c.address?.city if address?: Address and Address has a required city: string? What is the type of c.address?.city ?? "unknown"?
Show answer
The first is string | undefined, because address might be missing. The second is string, because ?? replaces the undefined case with a string.