Enums
What
An enum (short for “enumeration”) is a way to define a set of named constants. The simplest form is the numeric enum, where each member is assigned a unique number automatically.
How
You define an enum using the enum keyword. By default, values start at 0 and increment by 1:
enum Direction {
North, // 0
East, // 1
South, // 2
West, // 3
}
let myDir: Direction = Direction.North;
console.log(myDir); // 0
Numeric enums also support bidirectional mapping, meaning you can look up a name from its value:
const name = Direction[0]; // "North"
Why
Enums allow you to use meaningful identifiers like Direction.North in your code while storing simple, efficient numbers under the hood. This makes your logic easier to read and maintain compared to using “magic numbers.”
Summary
Numeric enums provide a clean way to manage related constants with the added benefit of automatic value assignment and reverse lookups.