TypeScript Reference ยท Classes, Enums and Decorators
TypeScript string enums
Reference for TypeScript string enums: members with string values, no reverse mapping, nominal-like typing, iteration, and when to prefer unions of literals.
A string enum gives every member an explicit string value. Unlike numeric enums, string members have no auto-increment, so each one needs an initializer. The values print readably in logs and survive serialization, which is the main reason people choose them over numeric enums.
String enums are stricter than numeric ones. A plain string is not assignable to a string-enum type, and two different string enums are never assignable to each other even when their values match.
enum Status { Active = "active", Paused = "paused", }
Try it
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.
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
enum Name { A = "a", B = "b", C = `${"c"}`, // allowed: a constant template literal }
| Part | Description |
|---|---|
| Initializer | A string literal (or a constant expression that is a string, such as a no-substitution template literal or another member). Required for every member. |
Returns: Name.A has the type Name.A, a subtype of Name, and the value "a" at run time.
Edge cases: the object has no reverse mapping, so Name["a"] is a type error and undefined at run time.
Usage notes
- The enum type is the union of its members. Inside a
switchover a string enum the compiler checks exhaustiveness, so a missing member makes the function's return type includeundefined. - A value from outside (JSON, a form, a URL) is only a
string. Validate it with a lookup likeObject.values(Status).includes(...)before casting. - Two enums with identical values are different types; this nominal feel is a feature when you want to avoid mixing up identifiers.
- A union such as
"active" | "paused"is lighter: it emits no JavaScript and accepts literals directly. See Enum alternatives. - Members can be used as property keys in mapped types:
Record<Status, number>requires every member. - Because string enums emit an object, they are not allowed under
erasableSyntaxOnly.
Related
- Numeric enums, Heterogeneous enums, const enums
- Enum types
- Tutorial: Enums