Sub topic 7
What Enums Compile to and Reverse Mapping
This chapter assumes you know basic TypeScript types, functions, object literals, and switch statements. The focus here is runtime behavior: what JavaScript TypeScript generates for enums and how numeric enums support reverse mapping.
Enums are runtime objects
A regular enum is more than a type annotation. TypeScript emits JavaScript that creates an object. Your program can read that object while it runs.
Consider this numeric enum:
enum Level {
Low,
Medium,
High,
}
console.log(Level.Low); // 0
console.log(Level.Medium); // 1
console.log(Level.High); // 2When no values are supplied, TypeScript starts at 0 and increases each value by one. You can also assign a starting value:
enum StatusCode {
Ok = 200,
NotFound = 404,
ServerError = 500,
}The members have the values 200, 404, and 500.
Numeric enum output
A simplified version of the JavaScript emitted for Level looks like this:
var Level;
(function (Level) {
Level[Level["Low"] = 0] = "Low";
Level[Level["Medium"] = 1] = "Medium";
Level[Level["High"] = 2] = "High";
})(Level || (Level = {}));The generated code assigns directions:
"Low"maps to0.0maps back to"Low"."Medium"maps to1.1maps back to"Medium".
The resulting object is similar to this:
{
Low: 0,
Medium: 1,
High: 2,
0: "Low",
1: "Medium",
2: "High"
}This two-way lookup is called reverse mapping.
enum Level {
Low,
Medium,
High,
}
console.log(Level.Medium); // 1
console.log(Level[1]); // "Medium"
const selected = Level.High;
console.log(Level[selected]); // "High"Reverse mapping can help when logging a numeric value received from another part of a program. However, it also means that a numeric enum creates a larger runtime object than its source code suggests.
String enums behave differently
String enums require explicit values:
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE",
}They create a forward mapping from member names to strings:
console.log(Color.Red); // "RED"
console.log(Color.Green); // "GREEN"They do not create a reverse mapping:
console.log(Color["RED"]); // undefinedThe runtime object is approximately:
{
Red: "RED",
Green: "GREEN",
Blue: "BLUE"
}String values are often easier to inspect in logs, network messages, and stored data. They also avoid accidental meaning changes when members are inserted. For example, adding a member to the middle of a numeric enum can change the automatically assigned numbers.
Numeric enum pitfalls
Numeric enums accept numbers in ways that can surprise you. A number may be accepted even when it does not name a declared member:
enum Level {
Low,
Medium,
High,
}
function setLevel(level: Level): void {
console.log(level);
}
setLevel(Level.High); // OK
setLevel(999); // May be accepted by TypeScriptAt runtime, 999 has no matching name:
console.log(Level[999]); // undefinedDo not treat reverse mapping as validation. If values come from a file, request, or user input, validate them before using them.
Numeric enums can also have duplicate values:
enum Result {
Success = 1,
Complete = 1,
}
console.log(Result[1]); // "Complete"The reverse mapping keeps only the last name assigned to a value. This can make debugging confusing.
When runtime output matters
Use a regular enum when you specifically want a named runtime object or need enum members at runtime. Numeric enums provide reverse mapping, but their generated object and implicit numbers can be drawbacks.
A string enum is often safer for values that cross a boundary, such as JSON, a database, or an API. Its values remain readable and stable:
enum Role {
Admin = "admin",
Viewer = "viewer",
}
const payload = JSON.stringify({ role: Role.Admin });
console.log(payload); // {"role":"admin"}A literal union has no runtime object at all. It is erased during compilation. Choose an enum when runtime names or values are useful, and choose a union when compile-time checking is enough.
> callout note > Reverse mapping is a feature of numeric enums, not string enums. It does not validate unknown numbers, and duplicate numeric values can overwrite earlier names.
Exercise
Exercise
What does Level[1] return for enum Level { Low, Medium, High }, and does Color["RED"] return a member name for enum Color { Red = "RED" }?
Show answer
Level[1] returns "Medium" because numeric enums create reverse mappings. Color["RED"] returns undefined because string enums create only forward mappings.