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?