Sub topic 2
Optional Properties with `?`
Assume you know basic TypeScript annotations, interfaces, type aliases, and union types such as string | undefined. This chapter explains how to declare properties that may be missing, how to read them safely, and how compiler settings change their meaning.
What an optional property means
An optional property uses ? after its name. It may be present on an object, but the object does not have to contain it.
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]",
};Both objects satisfy User. The first object omits email, while the second includes it.
When you read an optional property, TypeScript treats its value as possibly missing. Under strictNullChecks, User["email"] is effectively string | undefined.
function printEmail(user: User): void {
const email = user.email;
// email has the type string | undefined
console.log(email);
}The value undefined means that no usable string is available. Code must handle that possibility before calling string methods.
Optional properties versus `string | undefined`
These declarations look similar, but they describe different object shapes:
interface OptionalEmail {
email?: string;
}
interface RequiredEmail {
email: string | undefined;
}
const first: OptionalEmail = {}; // OK
const second: RequiredEmail = {}; // Error: email is required
const third: RequiredEmail = {
email: undefined,
}; // OK without exactOptionalPropertyTypesemail?: string means the property may be absent. email: string | undefined means the property must exist, but its value may be undefined.
This distinction matters when objects are serialized, merged, validated, or passed to an API. A missing key and a key whose value is undefined can have different meanings at runtime.
Reading optional values safely
Use a type guard when different behavior is needed for each case:
interface User {
name: string;
email?: string;
}
function sendEmail(user: User): void {
if (user.email !== undefined) {
console.log(`Sending to ${user.email.toUpperCase()}`);
} else {
console.log(`${user.name} has no email address`);
}
}Inside the if block, TypeScript narrows user.email from string | undefined to string. This narrowing allows string operations without an error.
Optional chaining, written ?., safely accesses a member only when the value exists. Nullish coalescing, written ??, supplies a fallback for null or undefined.
function contactLabel(user: User): string {
return user.email?.toLowerCase() ?? "no email on file";
}
console.log(contactLabel({ name: "Ada" }));
console.log(contactLabel({ name: "Grace", email: "[email protected]" }));The expression user.email?.toLowerCase() produces either a lowercase string or undefined. The ?? operator then chooses the fallback when the result is missing.
Do not use || as a replacement when an empty string is meaningful. || also replaces other falsy values, such as "", 0, and false. ?? replaces only null and undefined.
Missing versus explicitly undefined
The exactOptionalPropertyTypes compiler option makes the distinction between a missing property and an explicitly undefined property precise.
interface Settings {
theme?: string;
}
const defaults: Settings = {};
const custom: Settings = { theme: "dark" };
// With exactOptionalPropertyTypes enabled:
// const invalid: Settings = { theme: undefined };With this option enabled, theme?: string allows omission but does not allow theme: undefined. To allow both forms, declare the union explicitly:
interface FlexibleSettings {
theme?: string | undefined;
}
const settings: FlexibleSettings = {
theme: undefined,
};Enable this option when the difference between “not provided” and “provided as undefined” matters in your application.
How optional properties fit together
Exercise
What is the difference between email?: string and email: string | undefined?
Show answer
The first allows the email key to be omitted. The second requires the key to exist, but permits its value to be undefined.