Enums and alternatives
suggest changeString enums are useful when a runtime enum object is required.
enum Direction {
North = "north",
South = "south",
East = "east",
West = "west",
}
const heading: Direction = Direction.North;
console.log(heading);
For many APIs, an as const object plus an indexed access type is smaller and interoperates naturally with JavaScript.
const Status = {
Pending: "pending",
Complete: "complete",
} as const;
type Status = (typeof Status)[keyof typeof Status];
const current: Status = Status.Pending;
console.log(current);
A plain string-literal union, such as type Status = "pending" | "complete", is even simpler when no runtime lookup object is needed. Numeric enums also create reverse mappings at runtime, which can make iteration surprising; filter keys deliberately if you use them.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents