Sub topic 6
String enums
This chapter covers string enums: how you declare them, what TypeScript checks, what JavaScript they compile to, and where they behave differently from plain string values. It assumes you know basic TypeScript types, can write typed functions, and have read the earlier chapters on literal types, unions, and numeric enums.
What a string enum is
A string enum is an enum whose members are all initialized with string values. Each member must be given its value explicitly, because strings cannot be auto-incremented the way numbers can.
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE",
}
function paint(color: Color): void {
console.log(`Painting with ${color}`);
}
paint(Color.Red); // Painting with REDThe name on the left (Red) is what your code uses. The value on the right ("RED") is what exists at runtime. When you log the value, send it as JSON, or store it in a database, you get "RED", not a number. That is the main practical reason to prefer string enums over numeric enums: the values stay readable in logs, network traffic, and stored data.
The value does not have to match the name. Many codebases use values that match an external contract, such as an API field or a database column:
enum OrderStatus {
Pending = "pending",
Shipped = "shipped",
Delivered = "delivered",
Cancelled = "cancelled",
}The type checker treats enums as distinct types
A string enum type is stricter than a union of string literals. A plain string, even one with the same text as a member, is not assignable to the enum type.
enum Color {
Red = "RED",
Green = "GREEN",
}
function paint(color: Color): void {
console.log(color);
}
paint(Color.Red); // OK
paint("RED"); // Error: Argument of type '"RED"' is not assignable to parameter of type 'Color'.The reason is that an enum is a named type with its own identity. Two different enums with identical values are also not interchangeable:
enum Fruit {
Apple = "APPLE",
}
enum Brand {
Apple = "APPLE",
}
const fruit: Fruit = Brand.Apple; // Error: Type 'Brand.Apple' is not assignable to type 'Fruit'.This is sometimes described as nominal-like typing. TypeScript is structurally typed almost everywhere else, so string enums are one of the few places where the name of the type matters and the shape of the value does not.
The restriction runs in one direction only. An enum member is assignable to string, because every enum value is a string at runtime:
const label: string = Color.Red; // OK
const upper: string = Color.Red.toLowerCase(); // OK, string methods workSo you can pass an enum value to any function that accepts a string. You cannot pass an arbitrary string to a function that accepts the enum.
Comparisons
Comparing an enum value to a raw string literal is also flagged when the compiler can see the two have no overlap:
function isRed(color: Color): boolean {
return color === "RED"; // Error: This comparison appears to be unintentional because the types 'Color' and '"RED"' have no overlap.
}
function isRedOk(color: Color): boolean {
return color === Color.Red; // OK
}Always compare against the enum member, not its text.
Each member is its own type
When every member of an enum is a literal value, each member also becomes a type, and the enum type behaves like the union of its members. This lets you narrow and restrict values:
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",
}
type Vertical = Direction.Up | Direction.Down;
function climb(direction: Vertical): void {
console.log(`Going ${direction}`);
}
climb(Direction.Up); // OK
climb(Direction.Left); // Error: Argument of type 'Direction.Left' is not assignable to parameter of type 'Vertical'.This also makes exhaustive checks possible. Narrowing inside a switch removes one member per case, and a never assignment in the default branch fails to compile if you forget one:
function opposite(direction: Direction): Direction {
switch (direction) {
case Direction.Up:
return Direction.Down;
case Direction.Down:
return Direction.Up;
case Direction.Left:
return Direction.Right;
case Direction.Right:
return Direction.Left;
default: {
const unreachable: never = direction;
return unreachable;
}
}
}If you add Direction.Forward later, the never assignment reports an error in opposite and every similar function. That turns "I forgot to update a switch" into a compile-time error.
What string enums compile to
Unlike a type alias, an enum produces JavaScript. Here is the output for Color (the exact formatting depends on your compiler version and target):
var Color;
(function (Color) {
Color["Red"] = "RED";
Color["Green"] = "GREEN";
Color["Blue"] = "BLUE";
})(Color || (Color = {}));The compiler creates an object named Color and assigns one property per member. The object is real, exists at runtime, and adds bytes to your bundle.
No reverse mapping
A numeric enum writes two properties for each member: name to value and value to name. A string enum writes only the first.
enum Level {
Low,
High,
}
enum Color {
Red = "RED",
}
console.log(Level[0]); // "Low" (reverse mapping exists)
console.log(Color["RED"]); // undefined at runtime; TypeScript also rejects this lookupBecause there is no reverse mapping, the runtime object contains only the names as keys and the values as values. This has a useful side effect: you can list the members reliably.
console.log(Object.keys(Color)); // ["Red", "Green", "Blue"] (names)
console.log(Object.values(Color)); // ["RED", "GREEN", "BLUE"] (values)On a numeric enum, Object.keys returns both names and number strings, which is a common source of bugs. String enums avoid that problem.
Getting enum values from outside your program
Data from an API, a form, or a file arrives as a plain string. TypeScript will not let you pass it where a string enum is expected, and a type assertion such as value as Color only silences the compiler without checking anything. A wrong assertion produces a value that claims to be a Color but is not one.
The safe pattern is a type guard that checks against the runtime object:
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE",
}
function isColor(value: string): value is Color {
return (Object.values(Color) as string[]).includes(value);
}
function parseColor(input: string): Color {
if (!isColor(input)) {
throw new Error(`Unknown color: ${input}`);
}
return input;
}
console.log(parseColor("GREEN")); // GREEN
console.log(parseColor("PINK")); // throws Error: Unknown color: PINKThe cast as string[] is needed because Object.values(Color) has type Color[], and includes on that array only accepts Color. Widening to string[] allows the check.
Using enum values in other types
Sometimes you want the string literal types behind an enum, for example to describe an object that is keyed by the enum values. A template literal type converts the enum into the union of its values:
enum Color {
Red = "RED",
Green = "GREEN",
}
type ColorText = `${Color}`; // "RED" | "GREEN"
function paintByText(color: ColorText): void {
console.log(color);
}
paintByText("RED"); // OKEnum members can also be used as computed keys in mapped types. Record<Color, string> requires an entry for every member:
const labels: Record<Color, string> = {
[Color.Red]: "Red paint",
[Color.Green]: "Green paint",
};If you add Color.Blue later, the object labels fails to compile until you add a Blue entry. This is another way enums help you keep related code in sync.
Mixed enums
TypeScript allows an enum to mix string and numeric members. These are called heterogeneous enums.
enum Mixed {
No = 0,
Yes = "YES",
}This is legal but rarely a good idea. It mixes the reverse-mapping behavior of numeric members with the plain behavior of string members, so Object.values returns a blend of names, numbers, and strings. Pick one kind per enum.
Pitfalls and edge cases
- Initializers are required. In a string enum, every member after a string member needs an explicit initializer. A bare
Blue,afterGreen = "GREEN",is an error because the compiler cannot auto-increment from a string. - Duplicate values are allowed. Two members can share a value, such as
A = "x"andB = "x". The compiler does not warn. They are different member types but equal at runtime, which can confuse switch statements andRecordkeys. - Casing and value drift. The value is just a string. If your API sends
"Pending"and the enum says"pending", the type guard rejects the input at runtime. The compiler cannot catch this, so test the boundary. - Enums add runtime code. Even in a project that is otherwise only types, an enum emits an object. Tools that strip types without full type information (some transpilers and runners in "isolated" modes) may not support every enum feature, and ambient
const enumdeclarations are the usual trouble spot. The chapter on const enums covers that. - Declaration merging. Two
enumdeclarations with the same name merge into one. This is occasionally useful and often accidental. Avoid splitting an enum across files unless you intend to. - Serialization is easy, but the type is lost.
JSON.stringifywrites the raw string, andJSON.parsereturns a plainstring. The enum type only exists in your code, so you must validate as shown above.
When a string enum fits
String enums are a good choice when:
- the values are serialized and need to be readable (logs, JSON, databases);
- you want callers to use named members instead of raw strings, so renaming a value is a single change;
- you need a runtime object to iterate over the members, and you prefer the enum syntax to a constant object.
They fit less well when callers (including other packages) should be able to pass plain string literals, since the nominal-like check rejects those. A union of string literals or a constant object with as const avoids that friction. The later chapter on choosing between enums and unions compares the two in detail.
Summary
- A string enum assigns an explicit string to each member and compiles to a plain JavaScript object with one property per member.
- It has no reverse mapping, so
Object.keysandObject.valuesbehave predictably. - The enum type is nominal-like: raw strings are not assignable to it, and enums with equal values are not interchangeable. An enum member is assignable to
string. - Members are types, so you can build narrower unions and write exhaustive
switchstatements withnever. - Validate external strings with a type guard instead of an
asassertion. - `
${Color}` gives you the union of the enum's string values when you need it.
Exercise
Given enum Status { Active = "active", Inactive = "inactive" }, write a type guard isStatus(value: string): value is Status and say what happens with isStatus("ACTIVE"). Then explain why const s: Status = "active"; does not compile.
Show answer
Implementation: function isStatus(value: string): value is Status { return (Object.values(Status) as string[]).includes(value); }. The call isStatus("ACTIVE") returns false because the comparison is case-sensitive and the member value is "active". The assignment const s: Status = "active"; fails because string enums are nominal-like: a plain string literal is not assignable to the enum type, even when its text equals a member's value. Use Status.Active instead.
Exercise
A string enum Direction has members Up, Down, Left, and Right. You add a fifth member Forward = "FORWARD". You have a switch over Direction whose default branch assigns the value to a variable of type never. What happens at compile time, and why?
Show answer
The compiler reports an error in the default branch. After the four existing cases are handled, the remaining type is Direction.Forward, which is not assignable to never. The error points you to every switch that needs a new case.