0
0
Typescriptprogramming~3 mins

Why Enum member access in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could avoid confusing bugs caused by mistyped values with just one simple tool?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
const RED = 1;
const GREEN = 2;
const BLUE = 3;

function paint(color) {
  if (color === 1) { /* red paint */ }
}
After
enum Color {
  Red = 1,
  Green,
  Blue
}

function paint(color: Color) {
  if (color === Color.Red) { /* red paint */ }
}
What It Enables

You can write safer, clearer code by referring to meaningful names instead of magic numbers or strings everywhere.

Real Life Example

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.

Key Takeaways

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.