Reverse Mapping
In this page:
enum EnumName { Member = 1 }
const name = EnumName[1]; // "Member"
const value = EnumName.Member; // 1
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
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
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
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
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
enum Level { Low, Medium, High }
function displayName(level: Level) {
return Level[level];
}
console.log(displayName(Level.High));
- Using reverse mapping with a string enum, like
Status["DONE"], which does not exist. - Looping with
Object.keys(Color)and being surprised that it lists both names and numbers. - Assuming reverse mapping works with a
const enum, which has no runtime object.
- Numeric and string enums define named constants, and const and ambient enums cover more specialized cases.
- Numeric enums support reverse mapping from value back to name.
- Union types are an alternative to enums, so it helps to know when to choose each.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: