Typescript Enum – All You Need to Know
What is an Enum?
Enum is short for Enumeration, which is a list of named constant values. It is a way of defining a set of related constants, which can be easily accessed and managed in code. An enum type can be defined using the enum keyword in TypeScript.
Why use Enums?
Enums are a great way to organize and manage related constants in a structured and easy-to-use way. By using enums, you can avoid using hard-coded values and strings, which can lead to errors and make code harder to maintain. Also, enums provide a way of defining a set of related values that can be easily checked against.
Creating an Enum
To create an enum type in TypeScript, you need to use the enum keyword, followed by the name of the enum and a list of comma-separated enum members enclosed in braces. Each member of the enum must have a name and a value:
enum Direction {
Up = 1,
Down,
Left,
Right
}
In this example, we have defined an enum called Direction with four members: Up, Down, Left, and Right. The first member has a value of 1, and the remaining members will be assigned values automatically based on the value of the previous member.
Using Enums
To use an enum in TypeScript, you can refer to the enum member by its name:
enum Direction {
Up = 1,
Down,
Left,
Right
}
let direction: Direction = Direction.Up;
In this example, we have declared a variable called direction of type Direction, and assigned it the value Direction.Up. We can then use this variable to refer to the enum member.
Iterating over Enums
You can use the for..in loop to iterate over the members of an enum:
enum Direction {
Up = 1,
Down,
Left,
Right
}
for (let direction in Direction) {
console.log(direction);
}
This will output the names of all the members in the enum: Up, Down, Left, and Right.
FAQs
Q: Can enums have string values?
A: Yes, enums can have string values. By default, the value of the first member in an enum is 0, and the rest of the members will be assigned values automatically. However, you can specify a string value for any member of an enum:
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE"
}
Q: Can enums be used as keys in objects?
A: Yes, enums can be used as keys in objects. For example:
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE"
}
let colors = {
[Color.Red]: "#FF0000",
[Color.Green]: "#00FF00",
[Color.Blue]: "#0000FF"
};
This will create an object called colors with keys that are members of the Color enum.
Q: Can enums be merged with other types?
A: Yes, enums can be combined with other types, such as interfaces and classes, using the declaration merging feature of TypeScript. For example:
enum Direction {
Up = 1,
Down,
Left,
Right
}
interface Car {
direction: Direction;
}
class Vehicle implements Car {
direction: Direction = Direction.Up;
}
In this example, we have merged the Direction enum with the Car interface, and then implemented the interface in the Vehicle class.