Course contentsShow
← TypeScript
Lesson 481 of 1,79611. Literal TypesFree lesson

Literal Unions vs Enums: Trade-offs

Compare string literal unions to enums: literal unions have no runtime cost but lack reverse mapping features.

Literal Unions vs Enums: Trade-offs

You'll learn: How string literal unions compare to enums in terms of runtime cost, features, and practical trade-offs.

The Core Comparison

Both string literal unions and enums let you restrict values to a specific set of options, but they work differently under the hood.

A string literal union like type Direction = "north" | "south" | "east" | "west" is purely a compile-time construct. TypeScript erases it entirely during compilation — your JavaScript output contains no trace of the Direction type. The strings themselves already exist in your code.

Enums, on the other hand, generate actual JavaScript objects at runtime (unless you use const enum, which we haven't covered yet). This means extra code in your bundle.

The Runtime Cost Difference

// String literal union - zero runtime cost
type Status = "pending" | "approved" | "rejected";

// After compilation: nothing extra in JavaScript
const userStatus: Status = "pending";
// Compiles to: const userStatus = "pending";

The literal union disappears completely. Your JavaScript is identical to what you'd write without TypeScript.

The Reverse Mapping Limitation

Enums offer reverse mapping (looking up an enum member's name from its value), but literal unions cannot provide this feature because they don't exist at runtime. With literal unions, you're just working with plain strings — there's no object to query.

If you need runtime introspection or iteration over all possible values, literal unions alone won't help (though you can create a separate array of values manually).

When Each Shines

Literal unions win when bundle size matters and you don't need runtime features. They're perfect for API response types, configuration options, or any case where the strings speak for themselves.

Enums are useful when you need runtime iteration, reverse lookups, or want autocomplete on a dedicated namespace.

Key Takeaway: String literal unions have zero runtime cost but are compile-time only; enums add runtime code but enable features like reverse mapping.