Basic · 10 of 13 · 12 min read
Enums
The one TypeScript construct that emits JavaScript, the reverse mapping, the numeric soundness hole, and why a literal union usually wins.
- Enums
An enum names a set of related constants. It is also one of the very few TypeScript constructs that emits JavaScript — everything else on the type side disappears — and most of what makes enums awkward follows from that.
Numeric enums
enum Role {
Admin,
User,
Guest,
}
console.log(Role.Admin, Role.User, Role.Guest); // 0 1 2
Members count up from zero, and you can set them explicitly — subsequent members continue from where you left off:
enum Status {
Draft = 1,
Review, // 2
Published = 10,
Archived, // 11
}
console.log(Status.Review, Status.Archived); // 2 11
A numeric enum also builds a reverse mapping, because the emitted object has entries in both directions:
enum Role { Admin, User }
console.log(Role.User); // 1
console.log(Role[1]); // "User"
console.log(Object.keys(Role)); // ["0", "1", "Admin", "User"]
That is what the compiler emits — roughly:
var Role;
(function (Role) {
Role[(Role["Admin"] = 0)] = "Admin";
Role[(Role["User"] = 1)] = "User";
})(Role || (Role = {}));
The numeric hole
Any number is assignable to a numeric enum type. A long-standing compatibility decision, kept for flag-style enums:
enum Role { Admin, User }
function setRole(role: Role) { return role; }
console.log(setRole(99)); // 99 — accepted, and meaningless
String enums do not have the hole:
enum Stringy { Admin = "admin", User = "user" }
function setStringy(role: Stringy) { return role; }
// setStringy("admin"); // '"admin"' is not assignable to 'Stringy'
console.log(setStringy(Stringy.Admin)); // "admin"
String enums
enum Status {
Draft = "draft",
Published = "published",
}
console.log(Status.Draft); // "draft"
console.log(JSON.stringify({ s: Status.Draft })); // {"s":"draft"}
// console.log(Status["draft"]); // no reverse mapping
Two practical wins over numeric: the value is readable wherever it is logged or stored, and inserting a member does not renumber the ones after it — which, with numeric enums, silently changes the meaning of every row already in the database.
| Numeric enum | String enum | Literal union | |
|---|---|---|---|
| Emits runtime code | yes | yes | no |
| Reverse mapping | yes | no | n/a |
| Readable when serialised | no | yes | yes |
| Any value of the base type assignable | yes | no | no |
| Assignable from a plain string | no | no | yes |
| Iterable at runtime | yes | yes | only via a const array |
| Renumbering risk | yes | no | no |
The union alternative
type Role = "admin" | "user" | "guest";
function setRole(role: Role) { return role; }
const fromJson: string = "admin";
// setRole(fromJson); // 'string' is not assignable — still checked
setRole("admin"); // and a literal just works
Same autocomplete, same exhaustiveness checking, nothing emitted, and values that come straight out of JSON without conversion. When you also need the list at runtime, derive one from the other:
const ROLES = ["admin", "user", "guest"] as const;
type Role = (typeof ROLES)[number]; // "admin" | "user" | "guest"
function isRole(value: string): value is Role {
return (ROLES as readonly string[]).includes(value);
}
const input = "admin";
if (isRole(input)) console.log(`valid: ${input}`);
console.log(ROLES.join(", ")); // for a dropdown
That is the pattern most codebases settle on. One list, both uses, nothing emitted beyond the array you needed anyway.
const enum
Fully inlined at compile time — no object is emitted at all:
const enum Direction { Up = 1, Down = 2 }
console.log(Direction.Up); // emits: console.log(1 /* Direction.Up */)
Efficient inside one compilation, and broken across a module boundary: a consumer transpiling
file-by-file has nothing to inline from. That is why isolatedModules — which most modern setups
turn on — rejects them outright.
// With isolatedModules on:
// const enum Direction { Up }
// Cannot access ambient const enums when 'isolatedModules' is enabled.
Iterating an enum
The reverse mapping makes this fiddlier than it looks:
enum Role { Admin, User }
console.log(Object.keys(Role)); // ["0", "1", "Admin", "User"] — both directions
console.log(
Object.keys(Role).filter((k) => Number.isNaN(Number(k))), // ["Admin", "User"]
);
enum Status { Draft = "draft", Done = "done" }
console.log(Object.values(Status)); // ["draft", "done"] — string enums are clean
A const array has none of this ceremony, which is one more small argument for the union form.
When an enum is still right
- An existing codebase that uses them, especially Angular or NestJS, where they are idiomatic.
- Bit flags, where the numeric values are combined with
|and tested with&. - When you genuinely want a runtime namespace for the values and do not mind the emit.
enum Permission {
None = 0,
Read = 1 << 0,
Write = 1 << 1,
All = Read | Write,
}
const mine = Permission.Read | Permission.Write;
console.log((mine & Permission.Write) !== 0, mine === Permission.All); // true true
Common mistakes
Expecting an enum to be erased
Mistake. Assuming an enum costs nothing because “types disappear”.
Why it fails. It emits an object, so it survives into the bundle and cannot be tree-shaken
away by a bundler that cannot prove it is unused.
What to do instead. Know the trade-off, and reach for as const when you want the type
without the emit.
Storing numeric enum values
Mistake. Persisting Role.Admin as 0 in a database or an API payload.
Why it fails. Inserting a member later renumbers everything after it, so stored data silently
changes meaning. And 0 tells nobody reading a log anything.
What to do instead. A string enum or a literal union, so the stored value is the name.
Comparing an enum with a raw value
Mistake. if (role === "admin") against a string enum.
Why it fails. The literal is not assignable to the enum type, so the comparison does not
compile — the enum insists on its own members.
What to do instead. role === Role.Admin. If having to import the enum to compare is
annoying, that annoyance is the argument for a union.
Check yourself
4 questions from the bank on what you just read. Answering here does not affect your quiz history.
A numeric enum assigns values automatically, starting at zero.
What does this log?
enum Role {
Admin,
User,
Guest,
}
console.log(Role.User, Role[1]);Why do many codebases prefer a literal union over an enum?
A numeric enum is looser than it looks: its members are numbers, and so is anything else.
Why does the compiler accept setRole(99)?
enum Role { Admin, User }
function setRole(role: Role) {}
setRole(99);What is the main practical advantage of a string enum over a numeric one?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.