Codectionary / Developer documentation / TypeScript

exactOptionalPropertyTypes

exactOptionalPropertyTypes distinguishes an omitted optional property from an explicitly supplied undefined value.

What it is and why to use it

exactOptionalPropertyTypes distinguishes an omitted optional property from an explicitly supplied undefined value. With strict null checking, name?: string means the property may be absent, but if present it must be a string unless undefined is explicitly included. This is useful for patch objects where presence has meaning.

Common mistakes and limitations

This option requires strictNullChecks and is not included automatically by strict. It does not delete undefined fields or change object spread. If explicit undefined is part of the API, write name?: string | undefined deliberately.

Run this example

Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.

Terminal — compile and run

npx tsc example.ts --strict --target ES2022 --module commonjs
node example.js

Syntax

"exactOptionalPropertyTypes": true

Examples

exactOptionalPropertyTypes

Standalone TypeScript 5.8+ example; expected output is explained below.

type Patch = { name?: string };
const omitted: Patch = {};
const present: Patch = { name: "John" };
console.log("name" in omitted);
console.log("name" in present);
  1. The first object has no name property at all.
  2. The second object contains a string-valued name property.
  3. Compile with --exactOptionalPropertyTypes to reject { name: undefined } for this type. Reading an optional property may still yield undefined when it is absent.
  4. Expected output: false true

Best practices

  • This option requires strictNullChecks and is not included automatically by strict. It does not delete undefined fields or change object spread. If explicit undefined is part of the API, write name?: string | undefined deliberately.
  • Keep external-input validation separate from compile-time type descriptions.

Runtime & versions

Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

TypeScript Handbook

Specifications & further reading