In TypeScript, an enum (short for “enumeration”) is a way to define a set of named constants. Enums allow you to create a collection of related values that can be numeric or string-based. They are useful for representing a set of discrete values, such as days of the week, months of the year, or status codes.
Types of Enums
TypeScript supports two types of enums: numeric and string.
Numeric Enums
Numeric enums are the default type of enums in TypeScript. The first value in a numeric enum has a default value of 0, and each subsequent value is incremented by 1.
enum Direction {
Up,
Down,
Left,
Right
}
let directionUp: Direction = Direction.Up;
let directionRight: Direction = Direction.Right;
console.log(directionUp); // Outputs: 0
console.log(directionRight); // Outputs: 3
You can also specify custom numeric values for the enum members:
enum Direction {
Up = 1,
Down,
Left = 5,
Right
}
console.log(Direction.Up); // Outputs: 1
console.log(Direction.Down); // Outputs: 2
console.log(Direction.Left); // Outputs: 5
console.log(Direction.Right); // Outputs: 6
String Enums
String enums are enums where each member has a string value. They provide a clearer and more readable way to define enum values.
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT"
}
let direction: Direction = Direction.Up;
console.log(direction); // Outputs: "UP"
Using enum in switch case
Enums can be used to define and check for specific values within a set.
enum Status {
New,
InProgress,
Completed
}
function updateStatus(status: Status): void {
switch (status) {
case Status.New:
console.log("Starting new task.");
break;
case Status.InProgress:
console.log("Task is in progress.");
break;
case Status.Completed:
console.log("Task is completed.");
break;
}
}
updateStatus(Status.InProgress); // Outputs: "Task is in progress."