Course contentsShow
← TypeScript
Lesson 489 of 1,79612. EnumsFree lesson

Reverse Mapping in Numeric Enums

Access enum members by value in addition to name, a unique feature of numeric enums.

Reverse Mapping in Numeric Enums

What you'll learn: How numeric enums in TypeScript let you look up the enum member name using its numeric value, unlike string enums.


The Unique Feature of Numeric Enums

When you create a numeric enum in TypeScript, something special happens behind the scenes: TypeScript automatically generates bidirectional mappings. This means you can access enum members in two ways:

  • Forward mapping: from name to value (like a normal object)
  • Reverse mapping: from value back to name (unique to numeric enums!)

Think of it like a two-way dictionary. If you know a word, you can find its definition. But with numeric enums, if you know the definition (the number), you can also find the word (the enum name).

How It Works

enum Direction {
  Up,
  Down,
  Left,
  Right
}

// Forward mapping (name to value)
console.log(Direction.Up);      // 0
console.log(Direction.Down);    // 1

// Reverse mapping (value to name)
console.log(Direction[0]);      // "Up"
console.log(Direction[1]);      // "Down"

This works even with custom numeric values:

enum Status {
  Pending = 10,
  Active = 20,
  Completed = 30
}

console.log(Status.Active);     // 20
console.log(Status[20]);        // "Active"

Why This Matters

Reverse mapping is incredibly useful when you receive numeric data (from an API, database, or external source) and need to convert it to a readable name:

function displayStatus(code: number): void {
  const statusName = Status[code];
  console.log(`Status: ${statusName}`);
}

displayStatus(20);  // "Status: Active"

Key Takeaway: Numeric enums automatically create reverse mappings that let you retrieve the enum member name from its numeric value using bracket notation—a feature unique to numeric enums that doesn't exist in string enums.