TypeScript Fundamentals
Enums — Numeric, String, const Enums
Master TypeScript Enums: Numeric Enums, String Enums, Heterogeneous Enums, Reverse Mapping, const Enums, and modern object alternatives.
const Enums.
Unlike most TypeScript features which disappear after compilation, standard enums exist as real JavaScript objects at runtime.
1. Numeric Enums
Numeric enums auto-increment integer values starting from 0 (or a custom start index).
Reverse Mapping in Numeric Enums
Numeric enums generate a bidirectional reverse mapping from value to key:2. String Enums
In a String Enum, every member must be explicitly initialized with a string literal. String enums do not support reverse mapping, but produce readable values in logs.
3. const Enums (Zero Runtime Overhead)
Standard enums generate code objects in JavaScript output. If you want maximum runtime performance and zero JS bundle overhead, use const Enums.
const Enums are completely erased during compilation, and their values are inlined directly at invocation sites.Compiled JavaScript Output:
4. Modern Alternative: as const Objects
Many modern TypeScript codebases prefer Object literals with as const over TypeScript enum syntax because standard JavaScript objects require no custom TS-only compilation semantics.
5. Interactive Code Playground
Test Enum behavior and comparisons below:
6. Common Pitfalls & Edge Cases
as const object unions for strict runtime checks.const enum with isolatedModules: If building with Babel, Vite, or esbuild using --isolatedModules, const enum can cause build errors unless preserveConstEnums is enabled.7. Enum Types Comparison Table
| Feature | Numeric Enum | String Enum | const Enum | as const Object |
|---|---|---|---|---|
| Reverse Mapping | Yes (Enum[1]) | No | No | No |
| Runtime JS Code | Generates JS Object | Generates JS Object | Inlined (No JS Object) | Standard JS Object |
| Type Safety | Low (Allows any number) | High (Strict string match) | High | Highest |