Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~6 min readTypeScript
#TypeScript#Type System#Enums
3D illustration of glowing numeric step counters and string literal blocks being organized into an immutable enum registry

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 enum members are inlined at every use site and no object is emitted, which is why isolatedModules, 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.Ok is assignable to Status while the bare string "Ok" is not.
  • A member assigned without annotation widens to the enum type, not the member type; const bindings 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.keys returns roughly twice as many entries as there are members and Object.values returns names mixed with numbers.
  • An as const object 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

typescript
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, discouraged

The type-level signatures that matter:

typescript
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 member

keyof 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

FormEmitted runtimeReverse mappingInlined at useMember typesNotes
enum E { A } numericobject with both mapsyesnoliteral unionin-place modification possible at runtime
enum E { A = "a" } stringobject, names onlynonoliteral unionsafest enum default
const enum Enothingn/ayesliteral unionbreaks under per-file transpilation
declare enum Enothingn/anoliteral uniondescribes runtime code that exists elsewhere
as const objectthe objectnonoliteral union via keyof typeofno enum-specific checks, tree-shakes
union of string literalsnothingnon/aliteral unionno runtime value to iterate
mixed numeric/string enumobject, partial mappartlynoliteral unionflagged 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

typescript
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:

typescript
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:

typescript
enum Role { Admin = "ADMIN", Editor = "EDITOR" } Object.keys(Role); // ["Admin", "Editor"] Object.values(Role); // ["ADMIN", "EDITOR"]

2. const enum and file-by-file transpilation

typescript
// 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 by verbatimModuleSyntax) rejects ambient const enums with TS2748: Cannot access ambient const enums when 'isolatedModules' is enabled.
  • preserveConstEnums makes 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

typescript
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 Level

Since 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:

typescript
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

typescript
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

typescript
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 symptomCauseFix
TS2748: Cannot access ambient const enums when 'isolatedModules' is enabledconst enum from a .d.ts in a per-file builddeclare a regular enum or an as const object
TS2475: 'const' enums can only be used in property or index access expressionsan ambient const enum used as a valuepass a member instead, or stop using the enum as a value
TS2553: Computed values are not permitted in an enum with string valued membersa computed initializer next to string membersgive string members explicit values, or split the enum
TS1061: Enum member must have initializera member declared after a string member without a valuestate the value explicitly; only numeric members auto-increment
TS2452: An enum member cannot have a numeric nameenum E { 1 = "a" }rename the member
TS2474/TS2478: const enum initializer evaluated to a disallowed valueNaN, Infinity, or a non-constant expression in a const enumuse a regular enum
TS2322: Type '"admin"' is not assignable to type 'Role'a raw string compared with or passed as an enumuse Role.Admin, or validate and cast at the boundary
Dropdown renders twice the optionsObject.entries over a numeric enumuse a string enum or filter names
TS2367: This comparison appears to be unintentionalcomparing an enum member to a string, or a narrowed value to another membercompare against the member, not its underlying value
Enum value changes break stored datanumeric members renumbered when a member is insertedpin 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 tools

Small utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.

All TypeScript guides

More in TypeScript

All TypeScript guides

The guides filed next to this one in TypeScript, in library order.