What if you could avoid confusing bugs caused by mistyped values with just one simple tool?
Why Enum member access in Typescript? - Purpose & Use Cases
Imagine you have a list of colors and you want to use their exact names and values throughout your code. Without enums, you might write each color as a separate constant or string everywhere.
This manual way is slow and risky. You can easily mistype a color name or value, causing bugs that are hard to find. Changing a color value means hunting down every place it appears.
Enums let you group related values under one name. You access members by their names, which keeps your code clean, consistent, and easy to update in one place.
const RED = 1; const GREEN = 2; const BLUE = 3; function paint(color) { if (color === 1) { /* red paint */ } }
enum Color {
Red = 1,
Green,
Blue
}
function paint(color: Color) {
if (color === Color.Red) { /* red paint */ }
}You can write safer, clearer code by referring to meaningful names instead of magic numbers or strings everywhere.
In a game, you can define player states like Idle, Running, and Jumping as enum members, making it easy to check and update the player's current state without errors.
Enums group related values under one name.
Accessing enum members by name avoids mistakes and magic numbers.
Updating values is simple and safe in one place.