Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Classes, Enums and Decorators

TypeScript heterogeneous enums

Reference for heterogeneous enums in TypeScript: mixing string and number members, the initializer rule after a string, partial reverse mapping and why to avoid them.

A heterogeneous enum has both numeric and string members. TypeScript allows it, but it is rarely a good idea: the type of a value is harder to reason about, and the reverse mapping only exists for the numeric members.

The one rule to remember is about auto-increment. A member without an initializer must follow a numeric member; right after a string member the compiler cannot continue counting, so it reports an error.

TypeScript
enum Mixed {
  No = 0,
  Yes = "YES",
}

Try it

TypeScript Mixed members at run time

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 No initializer after a string member

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.

Syntax

TypeScript
enum Name {
  Num = 1,
  Str = "text",
  Next = 5,   // needs an initializer after a string member
}
Part Description
Number member Gets a reverse mapping entry: Name[1] === "Num".
String member Only the name-to-value entry exists.

Edge cases: an uninitialized member immediately after a string member is error TS1061 ("Enum member must have initializer"). The type of a variable declared as the enum is number | string in effect, so you need typeof checks to use it.

Usage notes

  • Heterogeneous enums are meant mostly for clever tricks with the JavaScript runtime object; for domain modeling they add confusion.
  • Object.values returns both numbers and strings, plus the reverse-mapped names for the numeric members, which surprises people iterating over them.
  • If you want a "yes/no/unknown" set of options, prefer a string enum or a union of literals; every value then has one type.
  • Heterogeneous enums share all the emit costs of ordinary enums: an object is generated, and the reverse entries for numeric members double the number of keys.