Course contentsShow
← TypeScript
Lesson 1216 of 1,79628. tsconfig in DepthFree lesson

exactOptionalPropertyTypes: Stricter Optional Handling

Distinguish between undefined and missing properties, disallowing explicit undefined assignments.

exactOptionalPropertyTypes: Stricter Optional Handling

What you'll learn: How TypeScript can distinguish between a property being absent versus explicitly set to undefined, and why this matters for type safety.

The Problem with Default Optional Handling

By default, TypeScript treats optional properties (prop?) as equivalent to properties that can be string | undefined. This means these two types are considered identical:

type WithOptional = {
  name?: string;
};

type WithUndefined = {
  name: string | undefined;
};

In practice, they're not truly the same. An optional property can be missing entirely, while a property typed as string | undefined can be explicitly set to undefined.

What exactOptionalPropertyTypes Does

When you enable exactOptionalPropertyTypes in your tsconfig.json, TypeScript enforces a stricter distinction:

  • name? means the property can be absent (not present in the object)
  • name can only hold values of type string, not undefined
  • You cannot explicitly assign undefined to optional properties
// exactOptionalPropertyTypes: true

type User = {
  name: string;
  nickname?: string;  // Optional, can be missing
};

const user1: User = { name: "Alice" };  // ✓ Valid
const user2: User = { name: "Bob", nickname: "Bobby" };  // ✓ Valid
const user3: User = { name: "Charlie", nickname: undefined };  // ✗ Error!

Why This Matters

This distinction is crucial for APIs that behave differently when a property is missing versus when it's explicitly undefined:

type UpdateRequest = {
  id: string;
  email?: string;
};

// Missing email = don't update email field
// email: undefined might accidentally erase the field

With exactOptionalPropertyTypes, you're forced to be explicit about your intent. If you genuinely want to allow undefined, you must write it in the type:

type UpdateRequest = {
  id: string;
  email?: string | undefined;  // Now undefined is allowed
};

Key Takeaway: exactOptionalPropertyTypes prevents accidental undefined assignments to optional properties, forcing you to distinguish between "property not provided" and "property explicitly set to undefined"—catching subtle bugs in object construction and API calls.