Sub topic 4
Missing versus undefined: exactOptionalPropertyTypes
This chapter assumes you know how to declare interfaces and type aliases, you can read union types such as string | undefined, and you have strict mode (specifically strictNullChecks) turned on. Earlier chapters showed how ? marks a property as optional and how to read optional values safely. Here you will see a gap in that model and the compiler flag that closes it.
The gap: absent is not the same as undefined
JavaScript objects can lack a property, or they can have the property with the value undefined. These are different objects at runtime:
interface Settings {
theme?: string;
}
interface LooseSettings {
theme?: string | undefined;
}
const absent: Settings = {};
const present: LooseSettings = { theme: undefined };
console.log("theme" in absent, "theme" in present); // false true
console.log(Object.keys(absent), Object.keys(present)); // [] [ 'theme' ]
console.log(JSON.stringify(absent), JSON.stringify(present)); // {} {}
console.log(absent.theme === present.theme); // trueReading .theme gives undefined in both cases, so plain property access cannot tell them apart. The in operator and Object.keys can. So can any code that copies properties, as the next sections show.
By default, TypeScript does not distinguish the two cases in its types. It treats theme?: string as if you had written theme?: string | undefined. Both of these assignments compile:
interface Settings {
theme?: string;
}
const a: Settings = {};
const b: Settings = { theme: undefined }; // accepted by defaultThat convenience is also a hole. The declaration says "if theme exists, it is a string", yet the object b has a theme key whose value is not a string.
What the flag changes
exactOptionalPropertyTypes makes ? mean exactly "this key may be absent". If the key is present, its value must match the declared type. undefined is accepted only if you write it into the type.
// tsconfig.json: { "compilerOptions": { "strict": true, "exactOptionalPropertyTypes": true } }
interface Settings {
theme?: string;
}
const s1: Settings = {}; // OK: key absent
const s2: Settings = { theme: "dark" }; // OK: key present, string value
const s3: Settings = { theme: undefined }; // Error
const s4: Settings = {};
s4.theme = undefined; // ErrorThe error text for the rejected lines ends with a hint: Type 'undefined' is not assignable to type 'string' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the type of the target. The hint names the fix for properties that really should accept undefined.
The following table summarizes what each declaration accepts.
| Declaration | Omit the key | Explicit `undefined` | A string | Column |
|---|---|---|---|---|
| `theme?: string` (flag off) | Yes | Yes | Yes | |
| `theme?: string` (flag on) | Yes | No | Yes | |
| `theme?: string \ | undefined` (either setting) | Yes | Yes | Yes |
| `theme: string \ | undefined` (either setting) | No | Yes | Yes |
The last row is the "required but may be undefined" case. The key must be written out, even if the value is undefined. That is a different contract from an optional property.
Reading is unchanged
The flag affects what you may write, not what you read. A read of an optional property still has the type string | undefined, because the key may be missing and a missing key reads as undefined. Everything from the previous chapter still applies: narrowing with !== undefined, optional chaining with ?., and defaults with ??.
interface Settings {
theme?: string;
}
function label(s: Settings): string {
return s.theme ?? "system default";
}This function compiles the same way with the flag on or off. What the flag adds is precision about the objects that reach it.
Why the difference matters at runtime
Three common operations treat a present-but-undefined key differently from an absent key.
Spreading and merging. A present key overwrites earlier values, even when it holds undefined:
interface Settings {
theme?: string;
fontSize?: number;
}
const defaults = { theme: "light", fontSize: 14 };
function applyOverrides(overrides: Settings) {
return { ...defaults, ...overrides };
}
console.log(applyOverrides({ fontSize: 16 }));
// { theme: 'light', fontSize: 16 }
console.log(applyOverrides({ theme: undefined, fontSize: 16 }));
// { theme: undefined, fontSize: 16 } (the default theme is lost)With the flag on, the second call does not compile, so the bug is caught where the undefined is written.
Serialization. JSON.stringify drops keys whose value is undefined, which is why the two objects at the start of this chapter print identically. Other serializers and database drivers may instead send null, throw, or write a column as NULL. A type that rules out undefined values keeps those behaviors out of your data.
Key inspection. in, Object.keys, Object.entries, hasOwnProperty and for...in all see the key. Code that counts keys or checks "theme" in obj to mean "the user set a theme" is only correct if present keys always carry real values.
Enabling the flag
Add it to tsconfig.json:
{
"compilerOptions": {
"strict": true,
"exactOptionalPropertyTypes": true
}
}Two points are easy to miss.
- The flag is not part of
strict. Turning onstrictdoes not enable it, so you must set it explicitly. - It only has an effect with
strictNullCheckson, whichstrictprovides. Without null checking,undefinedis assignable to everything and there is nothing to distinguish.
Fixing the errors it reports
Most errors come from code like { theme: maybeTheme } where maybeTheme is string | undefined. You have three fixes.
1. Omit the key when there is no value. This is usually the right fix when absence is the meaning you want:
interface Settings {
theme?: string;
}
function build(theme: string | undefined): Settings {
return theme === undefined ? {} : { theme };
}
function buildWithSpread(theme: string | undefined): Settings {
return { ...(theme !== undefined ? { theme } : {}) };
}The spread form is handy when you build an object with several optional keys.
2. Allow undefined explicitly. Do this when undefined is a meaningful value, for example "the caller deliberately cleared this field":
interface UpdateRequest {
nickname?: string | undefined;
}
const clear: UpdateRequest = { nickname: undefined }; // OK3. Remove the key with delete. TypeScript allows delete only on optional properties, and the flag makes that operation the precise way to say "make this absent":
interface Settings {
theme?: string;
}
const s: Settings = { theme: "dark" };
delete s.theme; // OK: theme is optional
console.log("theme" in s); // falseInteractions and edge cases
Utility types follow the flag. Partial<T> adds ? to each property, so under the flag it produces "may be absent" properties, not "may be undefined" ones. This surprises people who write patch APIs where undefined means "unset this field":
interface Profile {
nickname: string;
}
type Patch = Partial<Profile>;
const ok: Patch = {};
// const bad: Patch = { nickname: undefined }; // Error with the flag on
type PatchOrUndefined<T> = { [K in keyof T]?: T[K] | undefined };
const allowed: PatchOrUndefined<Profile> = { nickname: undefined }; // OKOnly properties are affected. Optional function parameters (function f(x?: string)), optional tuple elements and index signatures keep their usual behavior. A call f(undefined) is still fine.
Third-party types may not agree. Declaration files written without the flag in mind often declare foo?: string and then return objects where foo is undefined. If a library's types are wrong in that way, you may see errors when you pass your objects to it, or you may receive values that contradict the declared type. Setting skipLibCheck hides errors inside declaration files but does not correct their types. For a specific library, a wrapper type with | undefined at the boundary is the safest repair.
The flag affects assignability between types. An object type with theme?: string | undefined is not assignable to a type with theme?: string when the flag is on, because the source may hold undefined where the target forbids it. The reverse direction is fine. Expect this when passing "loose" objects into functions that declare "strict" parameters.
Deciding whether to use it
| Situation | Recommendation | Column |
|---|---|---|
| New project, you control the types | Enable it. The cost is small when you start with it. | |
| Code that merges, spreads or serializes optional objects | Enable it. The runtime differences above are where bugs come from. | |
| Large legacy codebase or heavy use of loosely typed libraries | Enable it per project in a monorepo, or defer it until the other strict flags are clean. | |
| Patch or update payloads where `undefined` means "clear" | Enable it and write ` | undefined` on those fields deliberately. |
The flag costs you convenience. You can no longer pass a possibly-undefined value straight into an optional property. In exchange, a property's type tells you what you can find in it: absent, or a value of the declared type.
How the pieces fit
Exercise
With exactOptionalPropertyTypes on, which of these lines is an error, and why? Assume interface Box { label?: string; size: number | undefined }. (a) const x: Box = { size: undefined }; (b) const y: Box = { label: undefined, size: 1 }; (c) const z: Box = { label: "a" };
Show answer
(b) and (c) are errors. (b) writes undefined into label, whose type is string when the key is present. (c) omits size, which is required: number | undefined is a required property that may hold undefined, not an optional one. (a) is fine: label is absent, and size is present with the allowed value undefined.
Exercise
Write a function withDefaults(overrides: { theme?: string }) that returns { theme: string }, using "light" when the key is absent. Then explain why, with the flag on, the line { ...{ theme: "light" }, ...overrides } is a safe way to do this, while with the flag off it can return an object whose theme is undefined.
Show answer
function withDefaults(overrides: { theme?: string }): { theme: string } { return { ...{ theme: "light" }, ...overrides }; } With the flag on, overrides can only lack theme or hold a string, so the spread either keeps "light" or replaces it with a string. With the flag off, the caller may pass { theme: undefined }, which compiles and overwrites "light" with undefined at runtime, while the return type still claims a string.
Exercise
A patch endpoint treats { nickname: undefined } as "clear the nickname" and {} as "leave it alone". Given interface Profile { nickname: string }, why does Partial<Profile> stop working for this under the flag, and what type fixes it?
Show answer
Under the flag, Partial<Profile> gives { nickname?: string }, which rejects an explicit undefined, so the "clear" request cannot be typed. Use a mapped type that adds | undefined: type PatchOrUndefined<T> = { [K in keyof T]?: T[K] | undefined };. Then {} means leave it alone and { nickname: undefined } means clear it.