TypeScript Course
TypeScript
/
Intermediate

Enums vs Union Types

Definition

A comparison between using TypeScript Enums and Literal Union Types (`type Role = 'Admin' | 'Guest'`) to manage distinct sets of values.

Explain Like I'm New

Union Types say: 'You must type the word "Admin" here'. Enums say: 'You must import my specific Enum object and use `Role.Admin` here'. In the modern React community, Union Types are vastly more popular because they are simpler and don't add bloat to your compiled JavaScript.

Real World Example

Migrating a codebase away from Enums because the compiled JavaScript output was bloated, replacing them all with simple String Unions.

Common Use Cases

  • •Choosing the right standard for your architecture

Interactive Example

// --- THE ENUM WAY ---
enum LogLevel {
  ERROR = "ERROR",
  WARN = "WARN",
  INFO = "INFO"
}
// Requires importing the Enum everywhere to use it
function logEnum(level: LogLevel, msg: string) { ... }
logEnum(LogLevel.WARN, "Memory high"); 

// --- THE UNION TYPE WAY (Modern Preferred Method) ---
type LogLevelType = "ERROR" | "WARN" | "INFO";

// No imports needed, just type the string. TS auto-completes it!
function logUnion(level: LogLevelType, msg: string) { ... }
logUnion("WARN", "Memory high");

Interview Questions

basic

  • Why do many modern TS developers dislike Enums?

intermediate

  • What happens to a Union Type during compilation compared to an Enum?

advanced

  • How do `const` enums attempt to solve the compilation bloat?

Flash Cards

Question

What happens during compilation?

Click to reveal answer
Answer

Union Types are 100% erased during compilation; they leave zero footprint in your JavaScript bundle. Enums, however, generate actual JavaScript objects (IIFEs). Using many Enums increases your final JS bundle size.

Question

Why do developers dislike Enums?

Click to reveal answer
Answer

1. They bloat the JS bundle. 2. Numeric enums behave strangely with Reverse Mapping. 3. String Unions are just easier to write (`variant="primary"` instead of `variant={ButtonVariant.Primary}`).