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

Type Safety: Enums vs Unions

Comparing the type safety guarantees of enums versus string-literal unions in assignment and narrowing.

Type Safety: Enums vs Unions

You'll learn how enums and string-literal unions compare when it comes to type safety guarantees in assignments and narrowing.

Both enums and string-literal unions help you restrict values to a specific set, but they differ in how strictly TypeScript enforces those restrictions.

Assignment Safety

String Enums are nominal types at the type level — only actual enum members can be assigned:

enum Status {
  Active = "active",
  Inactive = "inactive"
}

let status: Status = Status.Active; // ✓
status = "active"; // ✗ Error: Type '"active"' is not assignable to type 'Status'

String-Literal Unions are structural — any matching string literal works:

type StatusUnion = "active" | "inactive";

let statusU: StatusUnion = "active"; // ✓
const fromAPI: string = "active";
// statusU = fromAPI; // ✗ Error: Type 'string' is not assignable

Both prevent assigning arbitrary strings, but enums won't accept the raw string value, while unions will.

Narrowing Safety

Both narrow equally well with control flow:

function checkStatus(s: Status) {
  if (s === Status.Active) {
    // s is narrowed to Status.Active
  }
}

function checkStatusU(s: StatusUnion) {
  if (s === "active") {
    // s is narrowed to "active"
  }
}

The narrowing behavior is identical — both give you exhaustiveness checking and type-safe comparisons.

The Practical Difference

Enums reject raw string values even when they match, enforcing that you always use Enum.Member syntax. Unions accept matching literals directly. Both prevent invalid values and narrow reliably.

Key Takeaway: Enums enforce nominal typing (reject raw strings), while unions accept structural matches (any matching literal). Both provide strong type safety for narrowing and exhaustiveness checks.