Sub topic 4
Missing versus undefined: `exactOptionalPropertyTypes`
Assume you know basic TypeScript object types, interfaces, unions, and JavaScript object behavior. This chapter focuses on one distinction: a property can be missing, or it can exist with the value undefined. Those states often look similar when you read an object, but they can mean different things when you create, update, or serialize it.
Optional properties and `undefined`
An optional property uses ?:
interface User {
id: number;
nickname?: string;
}A User may omit nickname:
const ada: User = { id: 1 };
const grace: User = { id: 2, nickname: "Grace" };When you read nickname, TypeScript includes undefined because the property might be absent:
function displayName(user: User): string {
return user.nickname ?? "Anonymous";
}The expression user.nickname has the type string | undefined. The nullish coalescing operator, ??, uses the fallback when the value is undefined or null.
However, an optional property does not necessarily mean that callers should provide the property with an explicit undefined value. These two objects have different runtime shapes:
const missing = {};
const present = { nickname: undefined };
console.log("nickname" in missing); // false
console.log("nickname" in present); // trueThis difference affects object spreading, Object.keys, property checks, and JSON serialization.
A required property whose type includes undefined has a different contract:
interface RequiredNickname {
nickname: string | undefined;
}
const value: RequiredNickname = {
nickname: undefined,
};Here, nickname must exist. Its value may be a string or undefined.
What `exactOptionalPropertyTypes` changes
By default, TypeScript allows explicit undefined for an optional property. The compiler treats this assignment as valid:
interface Preferences {
color?: string;
}
const preferences: Preferences = {
color: undefined,
};Enable exactOptionalPropertyTypes to make the declaration more precise:
{
"compilerOptions": {
"strict": true,
"exactOptionalPropertyTypes": true
}
}With this option enabled, color?: string means exactly one of these choices:
- The
colorproperty is absent. - The
colorproperty exists and contains a string.
It does not allow an explicitly assigned undefined.
interface Preferences {
color?: string;
}
const defaults: Preferences = {}; // OK
const custom: Preferences = { color: "blue" }; // OK
// @ts-expect-error: undefined is not assignable to string
const unclear: Preferences = { color: undefined };If explicit undefined is meaningful in your API, include it in the type:
interface UpdatePreferences {
color?: string | undefined;
}
const reset: UpdatePreferences = {
color: undefined,
}; // OKThis version permits all three states: missing, a string, and explicit undefined.
Reading and updating optional properties
The option changes assignment checking, but reading an optional property still needs handling. The property may be absent:
function colorLabel(settings: Preferences): string {
if (settings.color !== undefined) {
return settings.color.toUpperCase();
}
return "default color";
}To remove a property, use delete rather than assigning undefined:
function clearColor(settings: Preferences): void {
delete settings.color;
}This preserves the distinction between an absent property and a present property whose value is undefined.
The option is especially useful for patch objects. Suppose a database update function interprets omission as “leave unchanged” and undefined as “clear the value.” The type should describe that policy explicitly:
interface UserPatch {
displayName?: string;
email?: string | undefined;
}
function applyPatch(user: User, patch: UserPatch): User {
const result = { ...user };
if ("displayName" in patch) {
result.displayName = patch.displayName!;
}
if ("email" in patch) {
result.email = patch.email;
}
return result;
}
interface User {
displayName: string;
email: string | undefined;
}The in operator checks whether the property exists, rather than whether its value is defined.
A useful mental model
The flag does not change JavaScript objects. It changes which object shapes TypeScript accepts during type checking. JavaScript can still create any of these shapes at runtime, so validate data received from APIs or other untyped boundaries.
Exercise
With exactOptionalPropertyTypes enabled, which declarations are valid for interface Config { mode?: string }?
Show answer
const a: Config = {}; and const b: Config = { mode: "dark" }; are valid. const c: Config = { mode: undefined }; is rejected. To allow c, declare mode?: string | undefined.