← Back to libraryQuestion 216 of 468
🔷TypeScriptIntermediate

Enums and Literal Types

📌 Definition:

Enums define a named set of constants (numeric or string). Literal types (union of specific values) often achieve the same intent more lightly and are usually preferred in modern TypeScript.

📖 Detailed Explanation:

enum Status { Active, Inactive } creates numeric constants (0, 1); enum Role { Admin = 'ADMIN' } creates string constants. Enums generate runtime objects (they exist in the emitted JS). Literal union types — type Status = 'active' | 'inactive' — are purely compile-time, lighter, and integrate better with narrowing and JSON. as const turns an object/array into deeply readonly literal types, a common way to derive unions (type Keys = typeof OBJ[keyof typeof OBJ]). Many teams prefer string literal unions or const objects over enums to avoid enum's runtime footprint and quirks (numeric enum reverse mapping).

🔑 Key Points:
  • Enums: named constants (numeric or string), exist at runtime
  • Literal unions ('a' | 'b'): compile-time only, lighter, JSON-friendly
  • as const derives readonly literal types/unions
  • Modern preference: string literal unions over enums
🌍 Real-World Example:

Instead of enum Env { Dev, Staging, Prod }, a test config uses type Env = 'dev' | 'staging' | 'prod' so values match the actual --env strings and narrow cleanly in switches.

🎯 Scenario-Based Interview Question:

Why do many TypeScript teams prefer type Status = 'open' | 'closed' over a string enum?