TypeScript & JavaScript · T69

Does TypeScript enum disappear after compilation?

A regular numeric TypeScript enum produces a runtime object with forward and reverse mappings. It does not disappear like a type alias.

The important bit
An as const assertion disappears, but its object remains. String enums and const enums have different output rules; this example uses TypeScript 5.9.3.

Understand it. Then fix it.

An enum is a runtime value.

An enum is an enumeration: named constants. A normal numeric enum produces an object with mappings both ways. Guest becomes zero, and zero maps back to Guest.

Badge.Guest // 0
Badge[0]    // "Guest"

Here is what the compiler adds.

Here is the generated JavaScript. That assignment creates the forward and reverse entries. String enums do not get the reverse mapping.

var Badge;
(function (Badge) {
  Badge[Badge["Guest"] = 0] =
    "Guest";
  Badge[Badge["Boss"] = 1] =
    "Boss";
})(Badge || (Badge = {}));

Plain object? Use as const.

If you just need named values, a plain object with as const works. The assertion preserves literal types, then disappears. The object itself stays.

const Badge = {
  Guest: 0, Boss: 1
} as const;

// JavaScript keeps:
const Badge = {
  Guest: 0, Boss: 1
};

Choose the runtime you need.

Keep an enum when its runtime behavior fits. For types only, a union emits nothing. Check your compiler output; const enum has different rules.

type Badge = "guest" | "boss";

Code blocks are teaching excerpts. Keep the surrounding error handling and application requirements.

Save the code excerpts ↓
Read the full transcript

Does enum disappear when TypeScript compiles? I wanted two labels, not a souvenir shop in my JavaScript. An enum is an enumeration: named constants. A normal numeric enum produces an object with mappings both ways. Guest becomes zero, and zero maps back to Guest. Here is the generated JavaScript. That assignment creates the forward and reverse entries. String enums do not get the reverse mapping. If you just need named values, a plain object with as const works. The assertion preserves literal types, then disappears. The object itself stays. Keep an enum when its runtime behavior fits. For types only, a union emits nothing. Check your compiler output; const enum has different rules. I ordered two labels. The compiler included a return department.

Go to the source