Preserve presence semantics
Model configuration objects where omission has a distinct meaning from explicitly supplying undefined.
TypeScript · Const
exactOptionalPropertyTypes makes optional property declarations exact: omission remains allowed, but undefined is not automatically added to the property's assignable values. Explicitly include undefined when that value should be permitted.
This compiler option makes optional property declarations exact: a ? permits the property to be absent, but does not automatically add undefined as an assignable value. Add | undefined when explicitly assigning undefined should be valid.
"exactOptionalPropertyTypes": true| Name | Type | Description |
|---|---|---|
exactOptionalPropertyTypes | boolean | Boolean compiler option controlling whether optional property types are interpreted exactly as written. |
?.undefined can behave differently from omission in runtime existence checks.undefined in the target property's type.interface UserDefaults {
colorThemeOverride?: "dark" | "light";
}
declare function getUserSettings(): UserDefaults;
const settings = getUserSettings();
settings.colorThemeOverride = "dark";
settings.colorThemeOverride = "light";
// Error: undefined is not an allowed assigned value.
// settings.colorThemeOverride = undefined;With the compiler option enabled, the optional property permits either omission or the explicitly declared string values; assigning undefined requires adding it to the property type.
Model configuration objects where omission has a distinct meaning from explicitly supplying undefined.
Prevent accidental clearing or invalid updates to optional fields in large object models.
Require API consumers to state explicitly when undefined is a supported value.
It changes optional properties so their declared type is used exactly instead of implicitly adding undefined. Therefore, a property declared as value?: string may be omitted, but assigning undefined is rejected.
Follow-up: How would you permit both omission and explicit undefined? Declare the property as value?: string | undefined.
An absent property and a present property whose value is undefined are different object states. The option preserves that distinction, preventing assignments that use undefined unless the declaration explicitly includes it.
Follow-up: Why can this matter at runtime? Existence checks can distinguish a missing key from a key whose value is undefined.
Enable exactOptionalPropertyTypes in compiler configuration, and also enable strictNullChecks because the option requires it. It is not automatically included by strict.
Follow-up: What happens if explicit undefined assignments are needed after enabling it? Add | undefined to the relevant property types.
strictNullChecksstrictoptional propertiesundefined