Enums and alternatives
Overview
Many languages have enums — named sets of constants — and TypeScript has them too. You’ll see them in older codebases and some libraries. But they’re one of the few TypeScript features that generate JavaScript, and modern TypeScript code increasingly avoids them. This lesson explains enums, their quirks, and the plain-JavaScript patterns that replace them.
Enums
enum Direction {
Up,
Down,
Left,
Right,
}
function move(direction: Direction) { … }
move(Direction.Up);By default members get the numbers 0, 1, 2… You can set values explicitly, including strings:
enum Status {
Active = "active",
Banned = "banned",
}An enum is both a type (Direction) and a value (an object you can use at run time, Direction.Up).
The catch: enums generate code
Everything else you’ve learned so far is erased when TypeScript becomes JavaScript. Enums aren’t: TypeScript has to write code for them. That has consequences:
-
Node.js can’t run them. Node’s built-in TypeScript support only strips types:
Text SyntaxError [ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX]: TypeScript enum is not supported in strip-only mode -
erasableSyntaxOnly(in this course’s tsconfig, and recommended for any project that strips types) reports them:Text error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled. -
Numeric enums are loosely typed and have reverse mappings.
Direction[0]is"Up", and the object contains both names and numbers, which surprises anyone who iterates over it.
Enums aren’t wrong — with tsc or a full compiler like tsx they work fine — but the alternatives are simpler and work everywhere.
Alternative 1: a union of string literals
For most uses, a literal union does everything you need:
type Status = "active" | "banned" | "pending";
function setStatus(status: Status) { … }
setStatus("active"); // ✓ autocompletes
setStatus("actve");
// error TS2345: Argument of type '"actve"' is not assignable to parameter of type 'Status'.- Zero run-time code.
- Values are readable in logs, JSON and databases (
"active", not0). - Narrowing and exhaustiveness checks work exactly as in Discriminated unions.
Alternative 2: a const object
When you also want the values as a real object — to loop over them, map them, or write Status.Active — use a const object with as const, and derive the type from it:
const Status = {
Active: "active",
Banned: "banned",
Pending: "pending",
} as const;
type Status = (typeof Status)[keyof typeof Status]; // "active" | "banned" | "pending"
function setStatus(status: Status) { … }
setStatus(Status.Active); // ✓ enum-like usage
setStatus("banned"); // ✓ a plain string works too
Object.values(Status); // ["active", "banned", "pending"] — no reverse mappingThe type line reads: “the type of the Status object, indexed by each of its keys” — that is, the union of its values. Using the same name for the value and the type is legal (values and types live in separate namespaces) and makes the pattern feel just like an enum.
For numeric constants, such as levels that need ordering, use numbers as the values:
const LogLevel = { Debug: 0, Info: 1, Warn: 2, Error: 3 } as const;
type LogLevel = (typeof LogLevel)[keyof typeof LogLevel]; // 0 | 1 | 2 | 3
if (level >= LogLevel.Warn) { … }Quick comparison
enum |
literal union | const object | |
|---|---|---|---|
| Run-time code | yes | none | a plain object |
| Works with type stripping | no | yes | yes |
X.Member syntax |
yes | no | yes |
| Iterate over values | awkward (reverse mapping) | no values to iterate | Object.values(X) |
| Narrowing & exhaustiveness | yes | yes | yes |
Reading enum code
You’ll still meet enums in existing projects and in library types. A few facts help when reading them:
enum E { A, B }— numeric, starting at 0.enum E { A = "a" }— string enum; no reverse mapping, and you can’t pass a plain"a"whereEis expected.const enum E { … }— members are inlined at compile time; also not erasable and discouraged in libraries.declare enum— an enum that exists somewhere else (in a.d.tsfile).
Rule of thumb: reach for a literal union first; use a const object when you need the values at run time; leave enums to code that already has them.
Log levels without an enum
The starter uses an enum, which Node can’t run and erasableSyntaxOnly rejects. Replace it with a const LogLevel = { Debug: 0, Info: 1, Warn: 2, Error: 3 } as const object and a matching type LogLevel derived from it. Then write levelName(level: LogLevel): string (the key for a value, e.g. 2 → "Warn"), shouldLog(level: LogLevel, minimum: LogLevel): boolean, and log(level: LogLevel, message: string, minimum: LogLevel = LogLevel.Info) that prints [WARN] Disk almost full only when the level is high enough. Separately, define type Theme = "light" | "dark" | "system" and a next(theme: Theme): Theme that cycles through them with a switch. Call everything to show it works.
enum LogLevel {
Debug,
Info,
Warn,
Error,
}
function log(level: LogLevel, message: string) {
if (level >= LogLevel.Info) {
console.log(`[${LogLevel[level].toUpperCase()}] ${message}`);
}
}
log(LogLevel.Warn, "Disk almost full");const LogLevel = { Debug: 0, Info: 1, Warn: 2, Error: 3 } as const;
type LogLevel = (typeof LogLevel)[keyof typeof LogLevel]; // 0 | 1 | 2 | 3
function levelName(level: LogLevel): string {
const entry = Object.entries(LogLevel).find(([, value]) => value === level);
return entry ? entry[0] : "Unknown";
}
function shouldLog(level: LogLevel, minimum: LogLevel): boolean {
return level >= minimum;
}
function log(level: LogLevel, message: string, minimum: LogLevel = LogLevel.Info): void {
if (shouldLog(level, minimum)) {
console.log(`[${levelName(level).toUpperCase()}] ${message}`);
}
}
log(LogLevel.Warn, "Disk almost full"); // [WARN] Disk almost full
log(LogLevel.Debug, "Cache hit"); // (hidden: below Info)
log(LogLevel.Debug, "Cache hit", LogLevel.Debug); // [DEBUG] Cache hit
type Theme = "light" | "dark" | "system";
function next(theme: Theme): Theme {
switch (theme) {
case "light": return "dark";
case "dark": return "system";
case "system": return "light";
}
}
console.log(next("light"), next("dark"), next("system")); // dark system lightSummary
- An
enumcreates both a type and a real JavaScript object; numeric enums also add a reverse mapping. - Enums generate code, so Node’s type stripping and
erasableSyntaxOnlyreject them. - A union of string literals is the simplest replacement:
type Theme = "light" | "dark". - When you also need the values at run time, use a const object
as constplustype X = (typeof X)[keyof typeof X]. - Unions and const objects narrow, autocomplete and check exhaustiveness just like enums.