Sub topic 8
Enums or literal unions: how to choose
This chapter assumes you can write TypeScript functions with type annotations and that you know the basics from earlier chapters. Those basics are literal types, unions of literals, as const, numeric and string enums, and what enums compile to. Here you use that knowledge to make a decision. Both tools model "one of a fixed set of values", so the choice comes down to runtime behavior, how values cross boundaries, and what your build tooling accepts.
The core difference
A union of literals exists only in the type system. It is erased when the code compiles, so nothing is left at runtime. The values are ordinary strings or numbers.
An enum is both a type and a real JavaScript object. The compiler emits code for it, and that object exists at runtime.
Most of the trade-offs follow from this one fact.
| Question | Literal union | Enum |
|---|---|---|
| Emits JavaScript? | No | Yes (an object, unless `const enum`) |
| Can you loop over the members at runtime? | Not by itself | Yes, with caveats for numeric enums |
| Accepts a plain literal like `"RED"`? | Yes | String enums: no. Numeric enums: partly |
| Matches JSON from an API directly? | Yes | Needs a conversion or a cast |
| Works with type-stripping tools? | Yes | Often not |
| Gives a named constant like `Color.Red`? | Only via a constant object | Built in |
Assignability: structural versus nominal-like
A union of literals is structural. Any value of the right literal type fits, no matter where it came from.
type Role = "admin" | "user";
interface ApiUser {
role: Role;
}
const parsed: ApiUser = JSON.parse('{"role":"admin"}');
const role: Role = parsed.role; // OK
const other: Role = "user"; // OKA string enum behaves differently. Its members are accepted only through the enum itself.
enum RoleEnum {
Admin = "admin",
User = "user",
}
function greet(role: RoleEnum): string {
return role === RoleEnum.Admin ? "Welcome back" : "Hello";
}
greet(RoleEnum.Admin); // OK
greet("admin"); // Error: Argument of type '"admin"' is not assignable to parameter of type 'RoleEnum'.This strictness has a benefit and a cost.
- Benefit: two enums with identical values are not interchangeable. This prevents mixing up, for example, a
RoleEnumand aPermissionLevelthat both happen to contain"admin". - Cost: every caller must import the enum. Tests, scripts, and other packages cannot pass a plain string. Data from JSON, a database, or a query string must be validated and cast before it can be used as the enum type.
With a union, the same boundary work is smaller. You still need to validate untrusted input at runtime, but the validated value already has the right type.
Iterating over the members
Sometimes you need the list of allowed values at runtime. Examples are filling a dropdown, validating a request, or generating documentation. A bare union cannot give you that list because the union is erased.
The usual fix is a constant object with as const, with a union type derived from it. This is the pattern from the earlier chapter on const assertions.
const Status = {
Active: "active",
Inactive: "inactive",
} as const;
type Status = (typeof Status)[keyof typeof Status]; // "active" | "inactive"
const allStatuses: readonly Status[] = Object.values(Status);
function isStatus(value: unknown): value is Status {
return typeof value === "string" && (allStatuses as readonly string[]).includes(value);
}
console.log(allStatuses); // [ 'active', 'inactive' ]
console.log(isStatus("active")); // true
console.log(isStatus("deleted")); // falseThe value Status and the type Status share a name on purpose. TypeScript keeps values and types in separate namespaces, so Status.Active refers to the object and Status in a type position refers to the union.
If you do not need named members such as Status.Active, a tuple is even shorter.
const STATUSES = ["active", "inactive"] as const;
type StatusValue = (typeof STATUSES)[number]; // "active" | "inactive"
function parseStatus(value: string): StatusValue {
const found = STATUSES.find((s) => s === value);
if (found === undefined) {
throw new Error(`Unknown status: ${value}`);
}
return found;
}Here the array is the single source of truth. The type and the runtime list cannot drift apart, which is the main risk when you write the union and a separate array by hand.
Iterating a numeric enum has a trap
Enums are real objects, so you can loop over them. For a string enum, Object.values(RoleEnum) returns the values as you would expect. A numeric enum also contains the reverse mapping, so its keys and values are doubled.
enum Level {
Low,
Medium,
High,
}
console.log(Object.values(Level)); // [ 'Low', 'Medium', 'High', 0, 1, 2 ]To get only the names you must filter out the numeric keys. Forgetting this is a common source of dropdowns that show each option twice.
Numeric enums are looser than they look
Numeric enums allow bit flags, which can be a real reason to choose them.
enum Permission {
None = 0,
Read = 1 << 0,
Write = 1 << 1,
Execute = 1 << 2,
}
const readWrite: Permission = Permission.Read | Permission.Write;
const canWrite = (readWrite & Permission.Write) !== 0;
console.log(readWrite, canWrite); // 3 trueThe value 3 is not a declared member, yet it is a valid Permission. Bitwise combination is the point of flag enums.
The same looseness is a hazard when you want a closed set. A variable of type number can be assigned to a numeric enum type without complaint, so the compiler does not guarantee the number is one of the members. A union such as 0 | 1 | 2 has no such gap. Prefer a union of literals or a string enum when you want the set to be closed.
Tooling constraints
Enums are one of the few TypeScript features that need code generation rather than simple removal of type annotations. This affects some build setups.
- Type-stripping runtimes. Tools that run TypeScript by deleting type syntax cannot handle enums, because an enum must be turned into JavaScript. Node.js's built-in type stripping is one example. It rejects enums unless you enable a transform mode.
erasableSyntaxOnly. TypeScript 5.8 added this compiler option. When it is on, enums (and a few other emitting features) are errors. Teams turn it on to keep their code compatible with type-stripping tools.isolatedModulesandconst enum. Compilers that handle one file at a time cannot always inline aconst enumfrom another file. Libraries that shipconst enumdeclarations can therefore cause trouble for consumers. Theconst enumsection of this tutorial covers the details.- Bundle size. Each enum adds an object and an immediately invoked function to the output. Unions add nothing.
If your project must run under a stripping tool, or you publish a library, literal unions with a constant object are the safer choice.
Debugging and readable values
Numeric enum values are opaque in logs and network traces. A log line showing status: 2 tells the reader nothing without the source. String enums and string unions print readable values, which makes them easier to diagnose and to store. If you persist values in a database, readable strings are also safer than numbers. Reordering an enum's members changes the numbers of implicit members, and old stored data then means something different.
enum Before {
A,
B,
C,
}
enum After {
A,
C, // inserted order changed: C is now 1
B,
}
console.log(Before.C, After.C); // 2 1If you use numeric enums that are stored or sent over a network, assign explicit numbers to every member and never change them.
Narrowing works for both
Exhaustiveness checking with never works for unions and enums alike. Adding a member to either makes an unhandled switch fail to compile.
enum Light {
Red = "RED",
Green = "GREEN",
}
function next(light: Light): Light {
switch (light) {
case Light.Red:
return Light.Green;
case Light.Green:
return Light.Red;
default: {
const unreachable: never = light;
return unreachable;
}
}
}So exhaustiveness is not a reason to choose one over the other.
A decision flow
Practical guidance
Use these rules as defaults and break them when you have a reason.
- Start with a literal union. It has no runtime cost, matches JSON, and accepts plain values from tests and other modules.
- Add a constant object with
as constwhen you need named access (Status.Active) or a runtime list of the values. - Choose an enum when you want values from different sets to be incompatible, when you need bit flags, or when the existing codebase already uses enums consistently. Match the codebase before you introduce a second style.
- Use string enums rather than numeric enums unless you need flags or must match a numeric protocol.
- Avoid
const enumin code that others consume. The inlining behavior depends on compiler settings.
Whichever you choose, validate data at the boundary. A type annotation on JSON.parse output does not check anything at runtime. A function like isStatus above does.
Exercises
Exercise
A function accepts Color, a string enum with Red = "RED". A teammate calls it as paint("RED") and gets a compile error. Name two ways to change the design so the call is accepted, and state one trade-off of each.
Show answer
Option 1: replace the enum with a literal union (type Color = "RED" | "GREEN"). The call is accepted, but you lose the runtime object and the nominal-like separation from other string sets. Option 2: use a constant object with as const and a derived union (type Color = (typeof Color)[keyof typeof Color]). Plain strings are accepted and Color.Red still works at runtime, but you must keep the object as the single source of truth and write the type derivation yourself.
Exercise
You have const ROLES = ["admin", "user", "guest"] as const;. Write the type Role derived from it, and a function isRole(value: string): value is Role that checks membership at runtime.
Show answer
type Role = (typeof ROLES)[number];
function isRole(value: string): value is Role {
return (ROLES as readonly string[]).includes(value);
}
The type is "admin" | "user" | "guest". The cast to readonly string[] is needed because includes on the tuple only accepts the three literal types, not an arbitrary string.
Exercise
Why does Object.values(Level) return six items for a numeric enum with three members, and why does this not happen for a string enum?
Show answer
A numeric enum compiles to an object with a reverse mapping, so it holds both name-to-number entries and number-to-name entries. That gives six values for three members. A string enum has no reverse mapping, so it holds only the name-to-value entries.