Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท tsconfig: Type Checking Options

TypeScript exactOptionalPropertyTypes option

Reference for exactOptionalPropertyTypes: why an optional property may be missing but not undefined, how it differs from union types, and the error it reports.

In TypeScript a property declared as nickname?: string normally accepts three things: a string, a missing property, and an explicit undefined. At runtime these are different: "nickname" in obj is false for a missing property and true when it is set to undefined, and Object.keys and JSON serialization treat them differently.

exactOptionalPropertyTypes makes the type match that reality. With it on, nickname?: string means "a string, or absent". Writing undefined explicitly becomes an error unless you declare nickname?: string | undefined. The option is not part of strict; you must turn it on yourself.

TypeScript
interface User {
  name: string;
  nickname?: string;
}

Try it

TypeScript Missing and undefined are not the same

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript What the option rejects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Syntax

JSON
{ "compilerOptions": { "exactOptionalPropertyTypes": true } }
Part Description
Value true or false. Default: false. Not included in strict. Added in TypeScript 4.4.
Requires strictNullChecks to be on; without it undefined is in every type and the option has no meaning.
Error TS2375 for object literals and assignments, TS2379 for arguments, both mentioning 'exactOptionalPropertyTypes: true'.
Reading A read of obj.nickname is still string | undefined; the option only changes what can be written.

Usage notes

  • Opt in per property. Write nickname?: string | undefined where an explicit undefined is a legitimate state.
  • Deleting is allowed. delete obj.nickname works on an optional property, because the property can be absent.
  • Spreads and Partial<T>. Partial<T> makes properties optional in the exact sense; passing { ...x, key: undefined } to it fails. Update helpers often need | undefined added.
  • Library types. Some .d.ts files were written for the inexact meaning; a few calls may need undefined widened. This is the main cost of turning it on.
  • Not for index signatures or arrays: [] holes and Record<string, T> values are unaffected.
  • When it pays off: code that serializes to JSON, uses in checks, or merges option objects, where "not provided" must differ from "set to undefined".