Intermediate LevelJavaScript & TypeScript
What are TypeScript Enums (numeric vs string vs const enums) and why prefer union types?
❓ Interview Prompt: Compare numeric enums, string enums, const enums, and literal union types regarding JS code generation.
Enums allow defining a set of named constants:
Enum Varieties:
1
Numeric Enums: Auto-incrementing numbers starting at 0 (
enum Direction { Up, Down }). Generates reverse mapping objects in compiled JS.2
String Enums: Values explicitly assigned strings (
enum Status { Active = 'ACTIVE' }).3
Const Enums: Inlined directly at compile-time (
const enum Color { Red }); generates zero runtime JavaScript code object!Modern Best Practice (Unions vs Enums):
String literal union types (type Status = 'active' | 'inactive';) are usually preferred over Enums because they generate zero JS runtime code and interact cleanly with standard JS string literals.
Code Implementation Example
typescript
// String Enum
enum LogLevel {
INFO = 'INFO',
ERROR = 'ERROR'
}
// Const Enum (inlined at compile time)
const enum HttpMethod {
GET = 'GET',
POST = 'POST'
}
const method = HttpMethod.GET; // Compiles directly to: const method = "GET";
// Preferred Modern Alternative: String Union
type Role = 'admin' | 'editor' | 'viewer';
const currentRole: Role = 'admin'; // Clean string literal, no enum import needed!💡String enum vs const enum inlining vs string literal union types.
🎯 Interview Key Takeaway
Const enums inline values for zero JS output. String literal union types are often cleaner and simpler than traditional Enums.
#TypeScript#Enums#Unions#Intermediate
Back to all JavaScript & TypeScript Questions→