Enums in TypeScript are used to define a set of named constants. They provide a way to group related values together and give them a descriptive name. This makes the code more understandable, especially when dealing with values that have a specific meaning. For example, if you are building a game and you have different states like PLAYING
, PAUSED
, and GAME_OVER
, you can use an enum to represent these states.
In a numeric enum, if you don’t explicitly assign a value to the first member, it will be assigned the value 0
, and subsequent members will be auto - incremented by 1
.
enum GameState {
PLAYING,
PAUSED,
GAME_OVER
}
let currentState: GameState = GameState.PLAYING;
console.log(currentState); // Output: 0
In the above code, GameState.PLAYING
has the value 0
, GameState.PAUSED
has the value 1
, and GameState.GAME_OVER
has the value 2
.
You can also initialize the first member with a specific numeric value, and the subsequent members will be incremented accordingly.
enum Direction {
NORTH = 1,
EAST,
SOUTH,
WEST
}
let currentDirection: Direction = Direction.EAST;
console.log(currentDirection); // Output: 2
Here, Direction.NORTH
is initialized to 1
, so Direction.EAST
is 2
, Direction.SOUTH
is 3
, and Direction.WEST
is 4
.
In a string enum, each member must be initialized with a string literal or another string enum member. String enums are useful when you want more descriptive values.
enum Color {
RED = "RED",
GREEN = "GREEN",
BLUE = "BLUE"
}
let favoriteColor: Color = Color.GREEN;
console.log(favoriteColor); // Output: "GREEN"
TypeScript allows you to create enums that contain both string and numeric values. However, this is not very common and should be used with caution.
enum BooleanLikeHeterogeneousEnum {
No = 0,
Yes = "YES"
}
Numeric enums have an additional feature called reverse mapping. This means that you can look up a value by its name and also look up a name by its value.
enum Enum {
A
}
let a = Enum.A;
let nameOfA = Enum[a]; // Reverse mapping
console.log(nameOfA); // Output: "A"
ADMIN
, USER
, and GUEST
, use an enum to represent these roles.enum UserRole {
ADMIN,
USER,
GUEST
}
Enums in TypeScript are a powerful feature that allows you to define a set of named constants. They can be numeric, string, or heterogeneous. Numeric enums support reverse mapping, which can be useful in certain scenarios. By following common and best practices, you can use enums effectively to make your code more readable and maintainable.