TypeScript Enums: Numeric, String, const Enums, and Alternatives
How each enum form compiles, why numeric enums emit a reverse mapping, what const enums cost under per-file transpilation, and how an as const object replaces them.

An enum declares a named set of constants, and unlike almost everything else in TypeScript's type layer it emits runtime code. A numeric enum compiles to an object holding a forward mapping from member name to value and a reverse mapping from value back to name; a string enum compiles to the forward mapping alone. Nearly every rule that surprises people about enums — the reverse lookup, the inlining performed by const enum, why a string member cannot be computed, why an enum is assignable from a number in some builds and not others — follows from that emitted object and from the way the checker treats each member as its own literal type.
Quick Summary
- A numeric member without an initializer takes the previous member's value plus one, starting at 0; a string member always requires an initializer.
- Numeric enums emit a reverse mapping (
Status[200] === "Ok"); string enums do not, because distinct members may share a value. const enummembers are inlined at every use site and no object is emitted, which is whyisolatedModules,verbatimModuleSyntax, and file-by-file transpilers (esbuild, Babel, SWC) reject or break them.- Each member is a literal type and the enum type is the union of its members, so
Status.Okis assignable toStatuswhile the bare string"Ok"is not. - A member assigned without annotation widens to the enum type, not the member type;
constbindings and explicit annotations keep the literal. - An enum with a computed member loses its union structure and falls back to plain number assignability.
- Iterating a numeric enum at runtime yields both mappings, so
Object.keysreturns roughly twice as many entries as there are members andObject.valuesreturns names mixed with numbers. - An
as constobject plus a derived key union reproduces the type safety with no reverse map, no inlining, and no build-tool coupling.
Basic syntax and type signatures
enum Direction { Up, Down, Left, Right } // 0, 1, 2, 3
enum HttpStatus { Ok = 200, NotFound = 404, ServerError = 500 }
enum Role { // string enum
Admin = "ADMIN",
Editor = "EDITOR",
Viewer = "VIEWER",
}
enum Permission { // bit flags are ordinary numbers
None = 0,
Read = 1 << 0,
Write = 1 << 1,
Execute = 1 << 2,
}
const enum LogLevel { Debug, Info, Warn, Error } // inlined at use sites, no object
declare enum Ambient { A, B } // ambient: types only, nothing emitted
enum Mixed { No = 0, Yes = "YES" } // heterogeneous: legal, discouragedThe type-level signatures that matter:
type AnyDirection = Direction; // Direction.Up | Direction.Down | ...
type OneDirection = Direction.Up; // the member literal type
type RoleName = keyof typeof Role; // "Admin" | "Editor" | "Viewer"
type RoleValue = `${Role}`; // "ADMIN" | "EDITOR" | "VIEWER"
type RoleLabel = Record<Role, string>; // enum values usable as keys
declare function move(d: Direction): void;
move(Direction.Left); // ok
// move(0); // error: 0 is not a Direction memberkeyof typeof Role reads the emitted object's keys as a type; `${Role}` turns a string enum into a template literal union, which is what makes an enum usable in exhaustive string maps. typeof Role is the object type, which is why Role is both a value and a type but typeof Role is not the same type as Role.
Comparison of enum forms and their alternatives
| Form | Emitted runtime | Reverse mapping | Inlined at use | Member types | Notes |
|---|---|---|---|---|---|
enum E { A } numeric | object with both maps | yes | no | literal union | in-place modification possible at runtime |
enum E { A = "a" } string | object, names only | no | no | literal union | safest enum default |
const enum E | nothing | n/a | yes | literal union | breaks under per-file transpilation |
declare enum E | nothing | n/a | no | literal union | describes runtime code that exists elsewhere |
as const object | the object | no | no | literal union via keyof typeof | no enum-specific checks, tree-shakes |
| union of string literals | nothing | no | n/a | literal union | no runtime value to iterate |
| mixed numeric/string enum | object, partial map | partly | no | literal union | flagged by most lint configs |
The practical split is between const enum and everything else. const enum buys a few bytes per use site and costs compatibility with the toolchains that most projects actually run; if the code ships through Vite, esbuild, Next.js, or Jest with SWC, the non-const form is the only one whose semantics survive.
Practical edge cases and deep dives
1. The reverse mapping is a second, colliding namespace
enum Status { Ok = 200, Created = 201, Accepted = 202 }
Object.keys(Status); // ["200", "201", "202", "Ok", "Created", "Accepted"]
Object.values(Status); // ["Ok", "Created", "Accepted", 200, 201, 202]
for (const [k, v] of Object.entries(Status)) {
// first three pairs are ["200", "Ok"], then ["Ok", 200]
}Integer-like keys enumerate first, then the name keys, and the two sets interleave badly for any code that assumes Object.entries returns one entry per member. The classic bug is a form dropdown built with Object.entries(Status), which renders six options for a three-member enum. Two duplicates compound it: members with equal values share one reverse key, and the last declaration wins, so Status[200] returns "Accepted" if a later member also uses 200. Filtering by type works but is ugly:
const names = Object.keys(Status).filter((k) => Number.isNaN(Number(k)));A string enum avoids the whole class of problems because its emitted object has only names:
enum Role { Admin = "ADMIN", Editor = "EDITOR" }
Object.keys(Role); // ["Admin", "Editor"]
Object.values(Role); // ["ADMIN", "EDITOR"]2. const enum and file-by-file transpilation
// logging.ts
export const enum LogLevel { Debug, Info, Warn, Error }
// app.ts
import { LogLevel } from "./logging";
console.log(LogLevel.Warn); // emitted as console.log(2 /* Warn */)With tsc alone this is fine: the compiler sees the declaration and replaces every use with the numeric literal. A transpiler that handles one file at a time does not see logging.ts while compiling app.ts, so it emits a real property access on an object that was never generated, and the import fails at runtime with Cannot read properties of undefined. The compiler tries to protect against this:
isolatedModules(implied byverbatimModuleSyntax) rejects ambient const enums withTS2748: Cannot access ambient const enums when 'isolatedModules' is enabled.preserveConstEnumsmakes the compiler emit the object anyway, trading the size win for correctness.- A const enum used in a value position other than member access triggers
TS2475: 'const' enums can only be used in property or index access expressions...
The safe pattern for a shared package is a plain enum or an as const object. A const enum inside one compilation unit that nothing else imports is the only case where the inlining costs nothing.
3. Widening, literal members, and the "any number" hole
enum Level { Low, Medium, High }
let a = Level.Low; // type: Level (widened to the enum type)
const b = Level.Low; // type: Level.Low (literal member type)
const c: Level = 0 as Level; // unchecked cast, always possible
function setLevel(l: Level) {}
setLevel(Level.High); // ok
// setLevel(1); // error: 1 is not assignable to LevelSince TypeScript 5.0 every enum whose members are all literal values is a union enum, so a numeric literal that is not a member is rejected at the call site. The hole is runtime: values crossing a JSON boundary arrive as number and nothing checks them. That is why an enum is a type claim, not validation:
function parseLevel(raw: unknown): Level {
if (raw === 1 || raw === 2 || raw === 3) return raw as Level;
throw new Error(`invalid level: ${String(raw)}`);
}An enum with at least one computed member (enum E { A = "x".length }) drops out of union-enum behavior entirely, and from then on the compiler accepts any number for it — the exact behavior older TypeScript versions had for all numeric enums.
4. Exhaustive handling of an enum
enum Shape { Circle = "circle", Square = "square", Triangle = "triangle" }
function area(s: Shape, size: number): number {
switch (s) {
case Shape.Circle: return Math.PI * size ** 2;
case Shape.Square: return size ** 2;
case Shape.Triangle: return (Math.sqrt(3) / 4) * size ** 2;
default: {
const unreachable: never = s; // error here when a member is added
throw new Error(`unknown shape: ${String(unreachable)}`);
}
}
}The never assignment is the compile-time guarantee: once Shape gains a member, s is no longer never in the default branch and the function fails to build at exactly the place that needs a new case. The runtime throw covers the case that arrives from JSON with a value the compiler never saw. Without the assignment, a default: return 0 quietly handles every future member as a circle of area zero.
5. Replacing an enum with as const plus a union
export const Role = {
Admin: "ADMIN",
Editor: "EDITOR",
Viewer: "VIEWER",
} as const;
export type Role = (typeof Role)[keyof typeof Role]; // "ADMIN" | "EDITOR" | "VIEWER"
export function isRole(v: unknown): v is Role {
return typeof v === "string" && Object.values(Role).includes(v as Role);
}
function label(r: Role): string {
switch (r) {
case Role.Admin: return "Administrator";
case Role.Editor: return "Editor";
case Role.Viewer: return "Viewer";
}
}This form keeps autocompletion, literal types, and switch exhaustiveness under noImplicitReturns (the function has no fall-through), while producing a plain object that survives any bundler, serializes cleanly, and iterates exactly once per member. The costs are real but small: keyof typeof Role is noisier than Role, the type and the value share a name only by convention, and a lookup table keyed by the union (Record<Role, X>) is the only way to get an exhaustiveness error at definition time rather than at use.
Common mistakes and compiler errors
| Error or symptom | Cause | Fix |
|---|---|---|
TS2748: Cannot access ambient const enums when 'isolatedModules' is enabled | const enum from a .d.ts in a per-file build | declare a regular enum or an as const object |
TS2475: 'const' enums can only be used in property or index access expressions | an ambient const enum used as a value | pass a member instead, or stop using the enum as a value |
TS2553: Computed values are not permitted in an enum with string valued members | a computed initializer next to string members | give string members explicit values, or split the enum |
TS1061: Enum member must have initializer | a member declared after a string member without a value | state the value explicitly; only numeric members auto-increment |
TS2452: An enum member cannot have a numeric name | enum E { 1 = "a" } | rename the member |
TS2474/TS2478: const enum initializer evaluated to a disallowed value | NaN, Infinity, or a non-constant expression in a const enum | use a regular enum |
TS2322: Type '"admin"' is not assignable to type 'Role' | a raw string compared with or passed as an enum | use Role.Admin, or validate and cast at the boundary |
| Dropdown renders twice the options | Object.entries over a numeric enum | use a string enum or filter names |
TS2367: This comparison appears to be unintentional | comparing an enum member to a string, or a narrowed value to another member | compare against the member, not its underlying value |
| Enum value changes break stored data | numeric members renumbered when a member is inserted | pin explicit values for anything persisted |
Two habits keep enums from becoming a maintenance tax. First, treat the numeric auto-increment as a convenience for in-memory code only: every enum whose values are stored in a database, a cookie, a URL, or an API payload should carry explicit values, because inserting a member in the middle renumbers everything after it and silently reinterprets old data. Second, decide once per project between enum and as const objects and apply it consistently — mixed usage produces two incompatible notions of the same closed set, and the conversion between them (Role[key], as Role) is exactly the unchecked cast the union was supposed to remove.
Try matching browser tools
All toolsSmall utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related TypeScript guides
All TypeScript guidesTypeScript Generic Parameter Defaults: Syntax, Precedence, and Inference
When a default applies and when inference wins, defaults that reference earlier parameters, and how a defaulted type parameter keeps a library change non-breaking.
TypeScript Branded Types: Nominal Typing, Type Tags, and Validation
How a phantom property makes two strings incompatible, unique symbol brands, unit-typed numbers, and the places where a brand quietly disappears.
TypeScript Ambient Declarations: .d.ts Files, declare, and declare global
How declare and .d.ts files describe runtime values, wildcard modules for assets, declare global with var, and module augmentation of third-party types.
TypeScript Discriminated Unions: Exhaustiveness Checking and the never Type
Why the discriminant must be a literal, how never closes an exhaustive switch, and the duplicate-discriminant bug that lets a missing case compile.
More in TypeScript
All TypeScript guidesThe guides filed next to this one in TypeScript, in library order.