Enums and Their Trade-offs
Enums create named sets of values. Numeric enums have reverse mappings in emitted JavaScript, while string enums provide explicit string values. const enum can erase runtime enum objects in some compiler configurations, but it has tooling and publishing trade-offs, so library authors should understand how consumers compile the output.
For many application states, a string literal union plus a constant object is simpler and interoperates naturally with JSON. Choose an enum when its runtime representation and semantics are valuable, not merely because other languages use enums.
Literal union as an alternative
const Direction = {
Up: "up",
Down: "down",
Left: "left",
Right: "right"
} as const;
type Direction = typeof Direction[keyof typeof Direction];
function move(direction: Direction) {
console.log(direction);
}💡
as const preserves the values as literals, and typeof Direction[keyof typeof Direction] creates the union of those values. The object remains available at runtime.Key Takeaways
- Enums have runtime behavior depending on their kind and compiler settings.
- Literal unions work naturally with JSON string values.
as constpreserves literal values for type derivation.
Knowledge Check
What is one benefit of a string literal union for API states?