Course contentsShow
← TypeScript
Lesson 514 of 1,79612. EnumsFree lesson

Enums and exactOptionalPropertyTypes

Enums can create type-checking issues with strict flags, particularly when trying to represent optional enum-typed properties.

Enums and exactOptionalPropertyTypes

What You'll Learn

You'll learn why enums can cause surprising type errors when using the exactOptionalPropertyTypes compiler flag, and how to work around this limitation.

The exactOptionalPropertyTypes Flag

TypeScript's exactOptionalPropertyTypes flag changes how optional properties behave. By default, property?: T means the property can be T, undefined, or missing entirely. With this flag enabled, you cannot explicitly set an optional property to undefined—you can only omit it.

The Enum Problem

Enums become problematic with exactOptionalPropertyTypes because enum types don't naturally include undefined. Consider:

enum Status {
  Active,
  Inactive
}

interface User {
  name: string;
  status?: Status;  // Optional enum property
}

// With exactOptionalPropertyTypes enabled:
const user: User = {
  name: "Alice",
  status: undefined  // ❌ Error! Can't assign undefined
};

The compiler sees status?: Status as accepting only Status values or omission—not explicit undefined.

The Workaround

You must use a union type to allow both the enum and undefined:

interface User {
  name: string;
  status?: Status | undefined;  // Now explicit undefined is allowed
}

const user: User = {
  name: "Alice",
  status: undefined  // ✅ Works now
};

This makes the optionality explicit in both directions.

Key Takeaway: When using exactOptionalPropertyTypes, optional enum properties require the | undefined union to accept explicit undefined assignments, not just omission.