Enums provide enumerations for grouping together constants.
Basics
In TypeScript, enums can automatically "scale" / assign values to objects, part of the enum:
Exporting the enum as type
The problem with Enums & Alternatives
Enums are pretty much disabled in TypeScript by default. The reason is the Erasable Syntax Only flag, which is set to false by default. Erasable meaning disappearing at runtime. As enums create objects at runtime, they belong into this group.
Using as consts:
export const Status = { IDLE: 'idle', LOADING: 'loading', SUCCESS: 'success', ERROR: 'error', } as const;
// Then, exporting for type-usage:
export type StatusType = keyof typeof Status;
In detail
How to TS compiler turns enums into JS at runtime:
enum Direction {
Up = 'UP',
Down = 'DOWN',
Left = 'LEFT',
Right = 'RIGHT',
}
Resulting is:
var Direction;
(function (Direction) {
Direction["Up"] = "UP";
Direction["Down"] = "DOWN";
Direction["Left"] = "LEFT";
Direction["Right"] = "RIGHT";
})(Direction || (Direction = {}));
Const enums
On alternative to avoid generating runtime code is using const enum. These enums are less rich in features, but enough for most use cases.
console.log(Direction.Up) // Output: 'UP'
console.log(Object.keys(Direction)) // Won't work
console.log(Object.values(Direction)) // Won't work
Furthermore, you can't use computed enum values.
Resources
- When to use enums and when not: https://bluepnume.medium.com/nine-terrible-ways-to-use-typescript-enums-and-one-good-way-f9c7ec68bf15