Sub topic 7
What enums compile to and reverse mapping
This chapter assumes you can write TypeScript enums, as covered in the numeric and string enum chapters. It also assumes you know the basics of JavaScript objects and immediately invoked function expressions (IIFEs). By the end you will be able to read the JavaScript an enum produces, explain why numeric enums can be looked up in both directions, and predict the surprises that follow from that design.
Enums are not erased
Most TypeScript syntax disappears at compile time. Type annotations, interfaces, and type aliases leave no trace in the output. An enum is different: the compiler emits real JavaScript for it, so an enum is both a type and a value that exists at runtime.
The numeric enum from earlier chapters:
enum Level {
Low,
Medium,
High,
}compiles to code like this:
var Level;
(function (Level) {
Level[Level["Low"] = 0] = "Low";
Level[Level["Medium"] = 1] = "Medium";
Level[Level["High"] = 2] = "High";
})(Level || (Level = {}));The exact output depends on your target and compiler version. Newer versions may use let or var and slightly different formatting. The shape stays the same.
Reading the emitted code line by line
The output has three parts.
var Level;declares a variable with the enum's name.- The function body fills in an object, which the function receives as its parameter
Level. (Level || (Level = {}))passes the existingLevelobject if there is one. Otherwise it creates an empty object, assigns it toLevel, and passes that.
The line that does the work is Level[Level["Low"] = 0] = "Low";. JavaScript evaluates it from the inside out:
An assignment in JavaScript is an expression whose value is the assigned value. The inner assignment Level["Low"] = 0 stores 0 under the key "Low" and evaluates to 0. That 0 becomes the key in the outer assignment, which stores "Low" under the key 0. One line writes both directions.
Reverse mapping
The two-way table is called reverse mapping. You can look up a value from a name, and a name from a value:
enum Level {
Low,
Medium,
High,
}
console.log(Level.Medium); // 1
console.log(Level[1]); // "Medium"
console.log(Level["High"]); // 2
console.log(Level[2]); // "High"Reverse mapping is useful when you hold a number from outside your program and want a readable label for it. Examples are a status code read from a binary file or a value stored in a database column.
enum HttpStatus {
Ok = 200,
NotFound = 404,
ServerError = 500,
}
function label(code: number): string {
return HttpStatus[code] ?? "Unknown";
}
console.log(label(404)); // "NotFound"
console.log(label(418)); // "Unknown"TypeScript types HttpStatus[code] as string, so the compiler does not warn that the lookup can miss. The ?? "Unknown" fallback is the runtime guard the type system will not ask you to write.
Reverse mapping only applies to numeric members
A string enum has no reverse mapping. Its compiled output is simpler:
enum Color {
Red = "RED",
Green = "GREEN",
}var Color;
(function (Color) {
Color["Red"] = "RED";
Color["Green"] = "GREEN";
})(Color || (Color = {}));Each member gets one assignment. There is no Color["RED"] = "Red" entry. If it existed, a member's name and another member's value could collide. For example, Red = "Green" would clash with the key "Green". Skipping the reverse entry avoids that problem.
A heterogeneous enum mixes both kinds, and each member follows its own rule:
enum Mixed {
No = 0,
Yes = "YES",
}
console.log(Mixed[0]); // "No"
console.log(Mixed["YES"]); // undefinedMixing is legal but rarely a good idea. The same object then follows two different lookup rules.
The surprise: the object holds twice as many keys
Because a numeric enum stores entries in both directions, iterating over it gives more than you might expect:
enum Level {
Low,
Medium,
High,
}
console.log(Object.keys(Level));
// ["0", "1", "2", "Low", "Medium", "High"]
console.log(Object.values(Level));
// ["Low", "Medium", "High", 0, 1, 2]JavaScript lists integer-like keys first, in ascending order, and then string keys in insertion order. That is why the numbers come before the names.
To get only the names of a numeric enum, filter out the keys that look like numbers:
enum Level {
Low,
Medium,
High,
}
const names = Object.keys(Level).filter((key) => Number.isNaN(Number(key)));
const values = Object.values(Level).filter(
(v): v is Level => typeof v === "number",
);
console.log(names); // ["Low", "Medium", "High"]
console.log(values); // [0, 1, 2]The filter works because enum member names cannot be numeric literals. A key that converts to a number can only be a reverse entry. For a string enum no filtering is needed, and Object.values(Color) returns exactly ["RED", "GREEN"].
Explicit values and duplicates
Initializers change the numbers but not the mechanism:
enum Flag {
A = 1,
B = 2,
C = 4,
}The compiled code writes Flag[Flag["A"] = 1] = "A" and so on. Numbers also auto-increment from the previous member, so enum Step { First = 10, Second, Third } gives 10, 11, and 12.
Nothing stops two members from sharing a value:
enum Alias {
Old = 1,
Current = 1,
}
console.log(Alias.Old); // 1
console.log(Alias.Current); // 1
console.log(Alias[1]); // "Current"The forward lookups both work. The reverse entry for 1 is written twice, and the later write wins. If your code relies on reverse mapping, keep numeric values unique.
Computed members
A numeric enum member's initializer can be a constant expression, such as 1 << 2 or a reference to an earlier member. It can also be a computed expression, such as a function call:
function base(): number {
return 100;
}
enum Computed {
Fixed = 1 << 3,
Dynamic = base(),
Next = 200,
}
console.log(Computed.Fixed); // 8
console.log(Computed.Dynamic); // 100
console.log(Computed[100]); // "Dynamic"The compiler folds constant expressions into literal numbers. Computed ones stay as code in the emitted function. A member that follows a computed member needs its own initializer, which is why Next = 200 is written out above. Computed members mean the compiler cannot always know every value ahead of time, which matters for const enums, covered in a later chapter.
Enums can merge
The Level || (Level = {}) argument is not decoration. It lets you declare an enum with the same name more than once, and the declarations merge into one object:
enum Palette {
Red = "RED",
}
enum Palette {
Blue = "BLUE",
}
console.log(Palette.Red, Palette.Blue); // RED BLUEThe second IIFE receives the object the first one built and adds its entries. This is called declaration merging. It is occasionally used to extend an enum across files or in ambient declarations. In ordinary application code it is more likely to be an accident, such as two files declaring an enum with the same name in the same scope. For numeric enums, only one of the merged declarations may leave its first member without an initializer.
Type side and value side
An enum name carries two meanings, and they behave differently:
enum Level {
Low,
Medium,
High,
}
type LevelName = keyof typeof Level; // "Low" | "Medium" | "High"
type LevelValue = Level; // Level.Low | Level.Medium | Level.High
function show(level: Level): string {
return Level[level];
}
const nameKey: LevelName = "Medium";
console.log(show(Level[nameKey])); // "Medium"- Used as a type,
Levelmeans "one of the members". - Used as a value,
Levelis the runtime object. typeof Levelis the type of that object, andkeyof typeof Levelgives its names. The reverse numeric keys do not appear in this type.
This is the same typeof and keyof technique you use to derive a union from a constant object. It works on an enum for the same reason: an enum is a runtime object.
Since TypeScript 5.0, every enum is a union enum, and assigning a literal number that is not a member to the enum type is an error. Earlier versions accepted any number for a numeric enum type. Values that arrive at runtime are still unchecked, because the type system cannot see them.
Consequences of being real code
Because an enum generates runtime code, a few practical points follow.
- Bundle size. Each enum adds an object and an IIFE. Bundlers often cannot remove an unused enum, because the IIFE has side effects they must assume are important. A plain
as constobject is easier to tree-shake. - Type-stripping tools. Tools that remove types without compiling TypeScript, such as Node's built-in type stripping, cannot handle enums. An enum needs generated code, not just deleted annotations. TypeScript has a compiler flag,
erasableSyntaxOnly, that reports enums and other syntax that cannot be erased. Check your toolchain's documentation if you plan to rely on stripping. - Single-file compilers. Tools that compile one file at a time, such as Babel or esbuild, can compile regular enums. They have trouble with const enums that are declared in other files.
- JSON and logging. A numeric enum value serializes as a bare number, so
JSON.stringify({ level: Level.High })gives{"level":2}. A string enum serializes as a readable string. Reverse mapping can translate a number back, but only if the code doing the lookup has the enum.
Quick reference
| Enum kind | Forward entry (name to value) | Reverse entry (value to name) | `Object.keys` length for 3 members |
|---|---|---|---|
| Numeric | Yes | Yes | 6 |
| String | Yes | No | 3 |
| Heterogeneous | Yes | Only for numeric members | 3 plus one per numeric member |
Exercise
Given enum Size { Small = 1, Medium = 2, Large = 3 }, what does Object.keys(Size).length return, and what does Size[2] return? Then write a filter that returns only the member names.
Show answer
Object.keys(Size).length is 6, because each member creates a name entry and a reverse numeric entry: ["1", "2", "3", "Small", "Medium", "Large"]. Size[2] returns "Medium". To get only the names, use Object.keys(Size).filter((key) => Number.isNaN(Number(key))), which returns ["Small", "Medium", "Large"].
Exercise
Why does enum Tag { A = "a", B = "b" } not allow a lookup like Tag["a"] to return "A", and what does the compiled output look like for one member?
Show answer
String enum members get only a forward assignment, such as Tag["A"] = "a";. The compiler does not write a reverse entry for them, because a value of one member could collide with the name of another. Tag["a"] returns undefined at runtime, and TypeScript reports it as an error under strict settings. A reverse map for a string enum has to be built by hand.
Exercise
In the statement Level[Level["Low"] = 0] = "Low";, which assignment runs first, and why does the outer assignment end up using the key 0?
Show answer
The inner assignment Level["Low"] = 0 runs first. An assignment expression evaluates to the value that was assigned, so it evaluates to 0. The outer assignment then uses that 0 as its key and stores "Low" there, giving Level[0] = "Low".