How to Ban Explicit undefined in Optional TypeScript Fields with exactOptionalPropertyTypesBrief · digest for December 1
Brief≈ 2 min

How to Ban Explicit undefined in Optional TypeScript Fields with exactOptionalPropertyTypes

An optional field name?: string in TypeScript is trickier than it looks: by default, the compiler allows { name: undefined } just like {}. In JavaScript at runtime, those are different objects — the name key shows up in Object.keys, "name" in obj returns true, and spreading { ...base, ...patch } overwrites the existing value.

Back in TypeScript 4.4, the exactOptionalPropertyTypes flag was added to fix this. It isn't included in strict: true, so add it to tsconfig.json separately:

{
  "compilerOptions": {
    "strict": true,
    "exactOptionalPropertyTypes": true
  }
}

Once enabled, the compiler distinguishes a missing key from an explicit undefined. Here is how it behaves on a partial update type:

type Patch = { name?: string };

// Key is omitted completely — valid
const empty: Patch = {};
// String value — valid
const named: Patch = { name: "Ann" };
// Error: undefined is not in the property type
const bad: Patch = { name: undefined };

// If undefined should be allowed, add it explicitly
type NullablePatch = { name?: string | undefined };

Now PATCH payloads and config objects won't accidentally wipe out defaults. If older @types/* packages complain when you turn this on, fix the specific type or enable skipLibCheck: true.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 2