0
0
Typescriptprogramming~3 mins

Why Reverse mapping in numeric enums in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could instantly find a name from a number without writing extra code?

The Scenario

Imagine you have a list of numbered options, like days of the week, and you want to find the name of a day when you only have its number. Doing this by hand means writing extra code to check each number and return the right name.

The Problem

Manually writing code to find names from numbers is slow and easy to mess up. You have to keep updating your code if you add or change numbers. It's like having to remember every phone number and name yourself instead of looking it up quickly.

The Solution

Reverse mapping in numeric enums lets you automatically get the name from the number without extra code. TypeScript creates a two-way map so you can use the number to find the name easily, saving time and avoiding mistakes.

Before vs After
Before
function getDayName(num: number) {
  if (num === 0) return 'Sunday';
  else if (num === 1) return 'Monday';
  // and so on...
}
After
enum Days { Sunday, Monday, Tuesday }
const dayName = Days[1]; // 'Monday'
What It Enables

This makes your code cleaner and faster, letting you switch between numbers and names effortlessly.

Real Life Example

Think of a game where each level has a number and a name. Reverse mapping lets the game show the level name when it only knows the number, without extra work.

Key Takeaways

Manual lookups are slow and error-prone.

Reverse mapping automates number-to-name conversion.

It keeps code simple and easy to maintain.