0
0
Typescriptprogramming~3 mins

Why Numeric enums in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you never had to remember or update magic numbers again?

The Scenario

Imagine you have a list of related values like days of the week or status codes, and you write each one as a separate constant number in your code.

For example, you write: const MONDAY = 0;, const TUESDAY = 1;, and so on.

The Problem

This manual way is slow and error-prone because you have to remember each number and keep them consistent everywhere.

If you add or remove a day, you must update all the numbers manually, which can cause bugs and confusion.

The Solution

Numeric enums let you group these related numbers under one name, automatically assigning numbers for you.

This keeps your code clean, easy to read, and safe from mistakes.

Before vs After
Before
const MONDAY = 0;
const TUESDAY = 1;
const WEDNESDAY = 2;
After
enum Days {
  Monday,
  Tuesday,
  Wednesday
}
What It Enables

Numeric enums make your code easier to manage and understand by giving meaningful names to numbers automatically.

Real Life Example

Think of a traffic light system where you assign numbers to colors: red = 0, yellow = 1, green = 2. Numeric enums let you write enum TrafficLight { Red, Yellow, Green } and use these names instead of numbers everywhere.

Key Takeaways

Manual number assignments are hard to track and update.

Numeric enums group related numbers with meaningful names.

They reduce errors and make code clearer and easier to maintain.