Sub topic 3
Reading Optional Values: Narrowing, `?.` and `??`
Assume you know basic TypeScript syntax, interfaces, type aliases, union types, and JavaScript objects. This chapter focuses on reading an optional property after it has been declared with ?.
An optional property may be absent from an object. When you read it, TypeScript usually includes undefined in the result type.
interface User {
id: number;
name: string;
email?: string;
}
const ada: User = {
id: 1,
name: "Ada"
};
const grace: User = {
id: 2,
name: "Grace",
email: "[email protected]"
};
const firstEmail = ada.email; // string | undefined
const secondEmail = grace.email; // string | undefinedEven though grace.email exists in this particular object, the declared type says that email is optional for every User. Therefore, TypeScript treats every read as potentially producing undefined.
Narrowing with an explicit check
Narrowing is the process of reducing a broader type to a more specific type after a check. An if statement can narrow string | undefined to string.
function sendWelcomeEmail(user: User): void {
if (user.email !== undefined) {
console.log(`Sending email to ${user.email.toUpperCase()}`);
} else {
console.log(`No email for ${user.name}`);
}
}
sendWelcomeEmail(ada);
sendWelcomeEmail(grace);Inside the first branch, TypeScript knows that user.email is a string. Inside the else branch, it knows that the value is undefined.
A truthiness check also narrows the value:
function printEmail(user: User): void {
if (user.email) {
console.log(user.email.toLowerCase());
}
}However, truthiness checks reject every falsy value. That matters when an optional property can contain values such as 0, false, or an empty string. Use an explicit !== undefined check when those values are valid.
Optional chaining with `?.`
Optional chaining reads a property only when the value before ?. is not null or undefined. Otherwise, the whole expression evaluates to undefined.
function emailDomain(user: User): string | undefined {
return user.email?.split("@")[1];
}
console.log(emailDomain(ada)); // undefined
console.log(emailDomain(grace)); // example.comWithout optional chaining, calling split on a missing email would cause a runtime error. Optional chaining prevents that call.
You can chain several operations:
interface Account {
owner?: User;
}
function ownerName(account: Account): string | undefined {
return account.owner?.name?.toUpperCase();
}The return type remains string | undefined because either owner or name might be missing.
Supplying a default with `??`
The nullish coalescing operator returns its left side unless that value is null or undefined. Otherwise, it returns the right side.
function contactLabel(user: User): string {
return user.email?.toLowerCase() ?? "no email on file";
}
console.log(contactLabel(ada)); // no email on file
console.log(contactLabel(grace)); // [email protected]The combination ?. and ?? is common:
user.email?.toLowerCase()safely attempts the method call.- The expression produces
string | undefined. ??converts the missing case into a definitestring.
Do not automatically replace ?? with ||. The || operator uses the fallback for every falsy value, including "", 0, and false.
const displayName = user.email || "unknown";
const exactEmail = user.email ?? "unknown";For an email, an empty string might be invalid, so || could be intentional. For numeric or boolean properties, ?? is often the correct choice because it preserves valid zero and false values.
> callout note > Do not use a type assertion such as user.email as string merely to silence the compiler. If the property is absent at runtime, the assertion does not create a string. Narrow the value, use optional chaining, or provide a default.
Exercise
What does this function return when called with { id: 1, name: "Ada" }, and why? function label(user: User): string { return user.email?.toUpperCase() ?? "MISSING"; }
Show answer
It returns "MISSING". The optional email produces undefined, and ?? replaces null or undefined with the fallback string.