An enum is a way to define a set of named constants that can be used as a type.
Example 1: Default Numeric Enum
By default, enum members are assigned incrementing numeric values starting from 0.
enum Color {
Red, // 0
Green, // 1
Blue // 2
}
let c: Color = Color.Green; // c = 1
Example 2: Custom Numeric Values
You can manually assign values to enum members.
enum Color {
Red = 1, // 1
Green, // 2
Blue // 3
}
let c: Color = Color.Green; // c = 2
Example 3: Enum with Specific Values
You can also set custom values for each enum member.
enum Color {
Red = 1, // 1
Green = 2, // 2
Blue = 4 // 4
}
let c: Color = Color.Green; // c = 2
Accessing Enum by Value
You can access the name of the enum member by its value.
let colorName: string = Color[2]; // "Green"
console.log(colorName); // Displays 'Green'
Key Points:
- Numeric Enum: Enum values are automatically assigned starting from 0 unless specified.
- Custom Values: You can manually assign values to each enum member.
- Accessing by Value: You can retrieve the name of an enum member using its numeric value (reverse lookup).