Exact optional semantics
Concept and syntax
With exactOptionalPropertyTypes: true (and strict null checks), note?: string means the property may be absent, or present with a string; writing undefined is not allowed unless the declared value type includes it. With the option off, assigning undefined is allowed for this optional property. Reads can still yield undefined in either mode. At runtime "note" in item distinguishes an absent key from a present key with undefined. This lesson enables the option explicitly in addition to strict.
Working example
Compile standalone examples in a fresh directory with tsc --strict --exactOptionalPropertyTypes --target ES2022 --module commonjs --noEmitOnError main.ts, then node main.js.
interface Item { note?: string; }const absent: Item = {};const present: Item = { note: "ok" };const explicit: { note?: string | undefined } = { note: undefined };console.log("note" in absent, "note" in present, "note" in explicit);Expected output (one line per log):
false true trueCommon mistake
Intentionally invalid; check this snippet separately. Do not run it.
interface Item { note?: string; }const item: Item = { note: undefined };Expected compiler diagnostic: TS2375. Under exactOptionalPropertyTypes, explicitly present undefined is incompatible with note?: string. Omit note, or include undefined in the declared type if it is intentional.
Practice and recap
Compile the explicit undefined assignment once with exactOptionalPropertyTypes and once without it. Compare results and inspect the runtime in operator.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Exact optional semantics — knowledge check
Check the concept, apply it to a new choice, and interpret a compiler diagnostic.
With exactOptionalPropertyTypes enabled, which assignment fits note?: string?
Does reading note?: string still allow undefined with this option on?
With exactOptionalPropertyTypes enabled, which correction preserves the optional string contract?
interface Item { note?: string; }const item: Item = { note: undefined };