What if you could instantly find a name from a number without writing extra code?
Why Reverse mapping in numeric enums in Typescript? - Purpose & Use Cases
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.
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.
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.
function getDayName(num: number) {
if (num === 0) return 'Sunday';
else if (num === 1) return 'Monday';
// and so on...
}enum Days { Sunday, Monday, Tuesday }
const dayName = Days[1]; // 'Monday'This makes your code cleaner and faster, letting you switch between numbers and names effortlessly.
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.
Manual lookups are slow and error-prone.
Reverse mapping automates number-to-name conversion.
It keeps code simple and easy to maintain.