Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 96 ยท Basic Types

Enums

Learn TypeScript enums - numeric and string enums, reverse mappings, const enums, what enums compile to, and why many teams prefer literal unions and as const objects.

An enum is a named set of constants. Instead of scattering magic values like 0, 1, 2 or 'pending', 'paid' through your code, you declare them once (Direction.Up, OrderStatus.Paid) and TypeScript makes sure every value you pass around belongs to the set.

Enums are unusual in TypeScript, because they are one of the few features that are not just types. An enum declaration produces a real JavaScript object at runtime. That has advantages (you can loop over it, look up names) and costs (extra code, quirks, and incompatibility with tools that only strip types). This lesson teaches enums completely, then shows the lighter alternative many modern codebases use: literal unions plus an as const object.

Numeric enums

Declare an enum with the enum keyword and a list of members. Without initializers, members get the numbers 0, 1, 2, and so on:

TypeScript A numeric enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The last line prints an object with eight entries, not four:

TEXT
{
  '0': 'Up',
  '1': 'Down',
  '2': 'Left',
  '3': 'Right',
  Up: 0,
  Down: 1,
  Left: 2,
  Right: 3
}

That's the reverse mapping. For numeric enums, TypeScript generates both directions: Direction.Up is 0, and Direction[0] is 'Up'. It's handy for logging a readable name, but it also means Object.keys(Direction) returns the numbers as strings too, which surprises people who try to list the members.

Also notice that move has no return type annotation. The switch covers every member, so TypeScript knows the end of the function is unreachable, and the inferred return type is { x: number; y: number } without | undefined.

Choosing the numbers

You can set any member's value. Members without an initializer continue counting from the previous one:

TypeScript Initializers and reverse lookups

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

HttpStatus[418] prints undefined: the reverse map only has entries for real members. Under strict, the type of HttpStatus[code] is string, so TypeScript doesn't warn you about that undefined. Keep that in mind when you use reverse lookups on numbers that come from outside.

Members can be computed from other members or constant expressions, as Permission.All and the 1 << n shifts show. Bit flags are one of the few places where numeric enums are still a natural fit.

How safe are numeric enums?

Since TypeScript 5.0, assigning a numeric literal that isn't a member is an error, so const d: Direction = 7 fails. But any value of type number is still accepted wherever a numeric enum is expected, because numeric enums are designed to interoperate with plain numbers (think of flags combined with |). So const d: Direction = someNumber compiles even if someNumber is 99. String enums, next, are much stricter.

String enums

In a string enum, every member must be initialized with a string literal. There's no auto-increment and no reverse mapping:

TypeScript A string enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

String enums print nicely (status: 'paid') and survive JSON.stringify with meaningful values, which is why people often prefer them over numeric ones. Object.keys and Object.values behave as you'd expect because there are no extra reverse entries.

String enums are nominal: only the enum's own members are accepted, even when a plain string has exactly the same value. This example fails on purpose:

TypeScript A string is not an enum member (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript stops with main.ts(11,11): error TS2345: Argument of type '"paid"' is not assignable to parameter of type 'OrderStatus'. The value 'paid' is identical at runtime, but the type checker treats OrderStatus as its own type. This is a deliberate safety feature, and also a common annoyance: data from JSON or a URL is a string, so you need a check (a type guard) before you can treat it as an OrderStatus.

You can mix numbers and strings in one enum (a heterogeneous enum), but there's no good reason to, so avoid it.

Enum members as types

Each member of an enum whose members are all literals is also a type of its own, and the enum type is the union of its members. That lets you narrow to specific members:

TypeScript
enum Shape { Circle, Square }

interface Circle { kind: Shape.Circle; radius: number }
interface Square { kind: Shape.Square; size: number }

Here Circle['kind'] can only ever be Shape.Circle. This is the same idea as discriminated unions, which you'll study later, just with enum members as the tags.

Two type-level tools are useful with enums:

  • typeof Direction is the type of the enum object itself (with properties Up, Down, ...).
  • keyof typeof Direction is the union of member names: 'Up' | 'Down' | 'Left' | 'Right'. You'll meet keyof and typeof properly in keyof, typeof and Indexed Access Types.
TypeScript Names, values and exhaustive checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The default branch assigns level to a variable of type never. After all four cases, nothing is left, so level is never there and the assignment compiles. Add a fifth member like Fatal = 'fatal' and the assignment fails, pointing you straight at the switch you forgot to update. any, unknown, never and void explains never; this pattern appears again in Discriminated Unions.

const enums

A const enum is erased completely. Every use is replaced by the literal value, and no object is emitted:

TypeScript
const enum Unit {
  Px = 'px',
  Rem = 'rem',
}

const width = `${10}${Unit.Rem}`;
JavaScript
// emitted JavaScript
const width = `${10}${"rem" /* Unit.Rem */}`;

That saves a little code, but const enums have real drawbacks: you can't loop over them or do reverse lookups (there is no object), and they need whole-program information. Tools that compile one file at a time (esbuild, SWC, Babel, Node's type stripping) can't see a const enum declared in another file, so the isolatedModules setting flags uses that would break. Library authors are advised not to export const enums at all. In application code, plain enums or the alternatives below are usually the better choice.

What enums cost at runtime

Here is roughly what enum Direction { Up, Down } compiles to:

JavaScript
var Direction;
(function (Direction) {
  Direction[Direction["Up"] = 0] = "Up";
  Direction[Direction["Down"] = 1] = "Down";
})(Direction || (Direction = {}));

This is code TypeScript generates, not just strips. That matters for a growing part of the ecosystem:

  • Node.js can run .ts files directly by stripping types (node main.ts). Type stripping only deletes annotations; it can't generate the code above, so an enum throws a syntax error there.
  • The erasableSyntaxOnly compiler option (TypeScript 5.8+) makes tsc reject every construct that needs code generation, including enum, namespace and class parameter properties. With it enabled, an enum fails with error TS1294, "This syntax is not allowed when 'erasableSyntaxOnly' is enabled."

Our editor doesn't enable erasableSyntaxOnly, so enums run fine here. See The tsconfig.json File for where this option fits.

The modern alternative: unions and as const objects

Most of what enums do can be done with plain JavaScript values plus types. The pattern has two parts: an object frozen to literal types with as const, and a type derived from its values:

TypeScript An enum-like object with as const

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Using the same name for the value and the type is legal because values and types live in separate namespaces; that's exactly what an enum does too. The type line uses tools from later lessons: typeof turns the object into a type and [keyof typeof OrderStatus] collects its property types, see keyof, typeof and Indexed Access Types. The value is OrderStatus return type is a type predicate, covered in this, Parameter Destructuring and Type Predicates.

Often you don't even need the object. A plain union like type Status = 'pending' | 'paid' gives you autocompletion and typo checking with zero runtime code.

enum literal union as const object + union
Runtime code Yes (object, reverse map for numbers) None A normal object
Pass a plain literal ('paid') No (string enums) Yes Yes
Iterate over values Yes (watch reverse entries) No Yes
Works with type stripping / erasableSyntaxOnly No Yes Yes
Bit flags Natural Awkward Possible

For new code, start with a literal union. Add an as const object when you also need the list of values at runtime. Reach for enum when a codebase already uses them, when you want bit flags, or when you prefer the nominal "only this enum's members" behavior. Whatever you choose, you'll read plenty of enums in existing code, so it pays to understand them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given enum Color { Red, Green, Blue }, what does console.log(Color[1]) print?

    Numeric enums have a reverse mapping, so Color[1] looks up the name of the member whose value is 1, which is Green.
  2. 2. Given enum Size { Small = 1, Medium, Large = 10, Huge }, what is the value of Size.Huge?

    A member without an initializer continues counting from the previous member. Large is 10, so Huge is 11.
  3. 3. With enum Mode { On = 'on', Off = 'off' } and function set(m: Mode), does set('on') compile?

    String enum types are nominal. Only Mode.On is accepted, even though its runtime value is the string 'on'.
  4. 4. Why does node main.ts (Node type stripping) reject a file that declares an enum?

    An enum compiles to a runtime object built by generated code. Type stripping just erases annotations, so it cannot handle enums, namespaces or parameter properties.
  5. 5. For const Level = { Low: 'low', High: 'high' } as const;, which type is (typeof Level)[keyof typeof Level]?

    keyof typeof Level is 'Low' | 'High', and indexing the object type with those keys gives the union of the property types, 'low' | 'high'.

Summary

  • enum declares a named set of constants and emits a runtime object.
  • Numeric enums auto-increment from 0 (or from the previous value), support computed members and bit flags, and have a reverse mapping from value to name.
  • String enums need an initializer for every member, have no reverse mapping, and are nominal: plain strings aren't accepted.
  • Members of literal enums are types; keyof typeof E gives the member names; a never check makes switches exhaustive.
  • const enum inlines values and emits nothing, but breaks with one-file-at-a-time tools; avoid exporting them.
  • Enums aren't erasable syntax, so Node's type stripping and erasableSyntaxOnly reject them. Literal unions and as const objects are the lightweight alternative.

Next: Type Assertions and the Non-Null Operator