Enums are a powerful feature of TypeScript that allow developers to define a set of named constants. Enums can be used to represent a set of related values, such as the days of the week or the status of an order. In this tutorial, we'll explore how to use enums in TypeScript.
What are Enums?
Enums are a type of data structure that allow developers to define a set of named constants. Enums are useful for representing a set of related values that have a fixed set of values. For example, consider the following enum:
enum DaysOfWeek {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
}In this enum, we have defined a set of constants that represent the days of the week. Each constant has an underlying numeric value, starting from 0 for the first constant (Sunday) and incrementing by 1 for each subsequent constant.
Creating Enums
To create an enum in TypeScript, you use the enum keyword followed by the name of the enum, and then define each of the constants in the enum:
enum MyEnum {
Value1,
Value2,
Value3,
}The values of an enum are assigned automatically by TypeScript. By default, the first value is assigned the value 0, and subsequent values are incremented by 1. You can also specify the values of an enum explicitly:
enum MyEnum {
Value1 = 1,
Value2 = 2,
Value3 = 3,
}In this example, we have specified the values of the constants explicitly.
Using Enums
To use an enum in TypeScript, you can simply reference the name of the enum and the name of the constant:
enum MyEnum {
Value1,
Value2,
Value3,
}
const myValue = MyEnum.Value1;In this example, we have defined an enum called MyEnum with three constants, and then assigned the value of MyEnum.Value1 to a variable called myValue.
You can also use enums in switch statements:
enum MyEnum {
Value1,
Value2,
Value3,
}
const myValue = MyEnum.Value1;
switch (myValue) {
case MyEnum.Value1:
console.log("Value 1");
break;
case MyEnum.Value2:
console.log("Value 2");
break;
case MyEnum.Value3:
console.log("Value 3");
break;
}In this example, we have defined an enum called MyEnum with three constants, and then used it in a switch statement to log the name of the constant.
String Enums
In addition to numeric enums, TypeScript also supports string enums. String enums allow you to use strings as the values of the constants in the enum:
enum MyStringEnum {
Value1 = "Value 1",
Value2 = "Value 2",
Value3 = "Value 3",
}In this example, we have defined an enum called MyStringEnum with three constants, each with a string value.
Conclusion
Enums are a powerful feature of TypeScript that allow you to define a set of named constants. You can use enums to represent a set of related values, such as the days of the week or the status of an order. By using enums, you can make your code more readable and maintainable.