Working with Enum in Typescript
What is an Enum in Typescript?
An enum, short for "enumeration," is a convenient way to define a set of related constants in TypeScript. An enum can store multiple values under a single name — usually strings, numbers, or a combination of both — with each value representing a specific meaning.
Enums are ideal for logically grouping related constants that represent some kind of enumerated type. Enums are also useful for improving code readability, since they give context to the literal values used in code.
How to Create an Enum in Typescript
Creating an enum in TypeScript is easy. All you need to do is use the keyword enum
followed by the name of your enum. Then, you can define the values of the enum by assigning a string or number to each member:
enum Color {
Red,
Blue,
Green
}
You can also assign a specific value to each of the members when creating an enum:
enum Color {
Red = 0,
Blue = 3,
Green = 5
}
Using an Enum in Typescript
Once you’ve created an enum in TypeScript, you can use it in your code by referencing the enum name and its member. For example, if the enum you created was named Color
, you can reference its members like this:
let color: Color = Color.Blue; // 3
let colorName: string = Color[3]; // Blue
The code above sets the variable color
to the value 3 (which is the value of the Blue
member) and sets the variable colorName
to the string “Blue” (which is the name of the Blue
member).
By using enums, you can make your code more readable and organized while still maintaining flexibility.