Enums
| Numeric enums | |
| String enums | |
| const enums | |
| Prefer union types when possible |
Numeric enums
A numeric enum names a fixed set of numbers. Members get 0, 1, 2 by default, so they fit choices like directions or steps.
enum Direction {
Up,
Down,
Left,
Right,
}
const move: Direction = Direction.Up;
console.log(move);
String enums
A string enum gives every member a readable text value. Logs and network payloads stay clear because the value explains itself.
enum Role {
Admin = "ADMIN",
Editor = "EDITOR",
Guest = "GUEST",
}
const role: Role = Role.Admin;
console.log(role);
const enums
A const enum is inlined at compile time and leaves no object behind at run time. Use it for hot paths where every byte and lookup counts.
const enum Size {
Small,
Medium,
Large,
}
const box: Size = Size.Medium;
console.log(box);
Prefer union types when possible
A union of literals often beats an enum: no extra syntax, exact autocompletion, and errors that name the allowed values.
Pick enums when values are shared across modules or need reverse lookup, and unions for small local choices.
type DirectionName = "up" | "down" | "left" | "right";
function walk(step: DirectionName): void {
console.log(step);
}
walk("up");
Next: ES modules
Article author: Arthur Isaev