← Back to TypeScript Course | Chapter 19: Enums Deep Dive | Lesson 6 of 6

Reverse Mapping

Numeric enums in TypeScript generate a runtime mapping from names to numbers and from numbers back to names. This reverse mapping is a feature of regular numeric enums and does not apply to string enums in the same way.

Basic Reverse Mapping

A numeric enum can be indexed by its numeric value to retrieve the corresponding member name — Color[0] gives you back the string "Red" if that's what member 0 was called, going backward from value to name.

Example: Basic Reverse Mapping

typescript
enum Color {
  Red,
  Green,
  Blue,
}
console.log(Color[0]);

Inspecting Numeric Enum Objects

At runtime, regular numeric enums contain both a forward mapping (name to number) and a reverse mapping (number to name) baked into the same object, which is why this trick works without any extra code.

Example: Inspecting Numeric Enum Objects

typescript
enum Color { Red, Green, Blue }
console.log(Color.Red, Color[0]);

Reverse Mapping with Functions

A small helper function can wrap reverse mapping to turn a raw numeric enum value into a readable name for logging or display, keeping the indexing syntax out of application code.

Example: Reverse Mapping with Functions

typescript
enum Color { Red, Green, Blue }
function nameOf(value: Color): string {
  return Color[value];
}
console.log(nameOf(Color.Green));

String Enums and Reverse Mapping

String enums don't get this automatic reverse mapping, because their runtime values are already strings — there's no separate numeric key to map back from in the first place.

Example: String Enums and Reverse Mapping

typescript
enum Status {
  Pending = "PENDING",
  Done = "DONE",
}
// Status["PENDING"] does NOT exist -- string enums have no reverse mapping.
console.log(Status.Pending);

When Reverse Mapping Matters

Reverse mapping is handy for turning a stored numeric value into a display name, but use it deliberately, since it depends on the actual runtime enum object existing — something const enums specifically don't provide.

Example: When Reverse Mapping Matters

typescript
enum Level { Low, Medium, High }
function displayName(level: Level) {
  return Level[level];
}
console.log(displayName(Level.High));
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.