patterntypescriptnoneModerate
Enum Alternatives: as const Objects Are Safer Than TypeScript Enums
Viewed 0 times
TypeScript 3.4+
enumas conststring enumnumeric enumtree shakingenum alternative
Problem
TypeScript numeric enums have surprising behavior: numeric values are assignable to any enum type, reverse mappings pollute the compiled output, and they don't tree-shake well.
Solution
Use 'as const' objects instead of enums for safer, tree-shakeable, and more predictable behavior.
// BAD: numeric enum with surprising behavior
enum Direction { Up, Down, Left, Right }
const d: Direction = 999; // TypeScript allows this!
// GOOD: as const object
const Direction = {
Up: 'UP',
Down: 'DOWN',
Left: 'LEFT',
Right: 'RIGHT',
} as const;
type Direction = typeof Direction[keyof typeof Direction];
// 'UP' | 'DOWN' | 'LEFT' | 'RIGHT'
function move(dir: Direction) { /* ... */ }
move(Direction.Up); // OK
move('INVALID'); // Error
move(999); // Error — no numeric escape hatchWhy
Numeric enums in TypeScript allow any number to be assigned due to index reverse-mapping. String enums are safer but still generate extra runtime code. 'as const' objects compile to a plain object with zero overhead.
Gotchas
- The 'type Direction = typeof Direction[keyof typeof Direction]' boilerplate is verbose but necessary.
- as const objects can't be used directly as a type — you need the typeof extraction pattern.
- String enums are actually safer than numeric enums; if you must use enums, prefer string enums.
Revisions (0)
No revisions yet.