0
0
Typescriptprogramming~5 mins

Reverse mapping in numeric enums in Typescript

Choose your learning style9 modes available
Introduction

Reverse mapping helps you find the name of an enum member when you have its numeric value. It makes working with enums easier and clearer.

When you get a numeric value and want to know which enum name it matches.
When debugging and you want to print the enum name instead of just a number.
When you receive numeric enum values from an API and want to convert them back to readable names.
Syntax
Typescript
enum EnumName {
  Member1 = 0,
  Member2 = 1,
  Member3 = 2
}

// Reverse mapping example:
let name = EnumName[1]; // 'Member2'

Numeric enums automatically create reverse mappings from value to name.

Reverse mapping works only for numeric enums, not for string enums.

Examples
This prints the name 'Green' because 1 maps to Green in the enum.
Typescript
enum Colors {
  Red = 0,
  Green = 1,
  Blue = 2
}

console.log(Colors[1]);
Since Waiting is 6 (5 + 1), Status[6] returns 'Waiting'.
Typescript
enum Status {
  Ready = 5,
  Waiting,
  Done
}

console.log(Status[6]);
Reverse mapping finds 'Left' from the numeric value 3.
Typescript
enum Direction {
  Up = 1,
  Down = 2,
  Left = 3,
  Right = 4
}

let dirName = Direction[3];
console.log(dirName);
Sample Program

This program shows how to get the enum name from a number using reverse mapping.

Typescript
enum Weekday {
  Monday = 1,
  Tuesday,
  Wednesday,
  Thursday,
  Friday
}

// Get name from number
const dayName = Weekday[3];
console.log(`Day 3 is ${dayName}`);
OutputSuccess
Important Notes

Reverse mapping only works with numeric enums, not string enums.

If you assign custom numbers, reverse mapping uses those numbers to find names.

Be careful: if two members have the same value, reverse mapping returns the last one defined.

Summary

Numeric enums create a two-way map: name to number and number to name.

Reverse mapping helps convert numbers back to enum names easily.

This feature is useful for debugging and working with numeric enum values.