gotchaModeratepending
TypeScript enums are not type-safe at runtime -- use const objects
Viewed 0 times
enumconst objectas constsatisfiesstring unionreverse mapping
typescriptnodejs
Error Messages
Problem
TypeScript numeric enums accept any number at runtime, reverse-mapping is confusing, and they emit JavaScript code. String enums are better but still have issues with tree-shaking and bundle size.
Solution
Use const objects with as const instead of enums. They are fully type-safe, tree-shakeable, and produce no runtime code beyond the object itself. Use satisfies for validation.
Why
TypeScript enums were designed early and have legacy behavior. Numeric enums create reverse mappings (enum[0] = 'value'). They are not a zero-cost abstraction.
Code Snippets
Const objects vs enums
// AVOID: TypeScript enum
enum Status { Active, Inactive }
const s: Status = 999; // No error! Accepts any number
// PREFER: const object
const Status = {
Active: 'active',
Inactive: 'inactive',
} as const;
type Status = typeof Status[keyof typeof Status];
// type Status = 'active' | 'inactive'
function setStatus(s: Status) { /* ... */ }
setStatus(Status.Active); // OK
setStatus('active'); // OK
// setStatus('invalid'); // Compile error!Revisions (0)
No revisions yet.