Sub topic 9
as const objects or enums
This chapter compares two ways to name a fixed set of values in TypeScript: the enum keyword and a plain object marked as const. It assumes you know the following:
- Basic TypeScript types.
- Union and literal types such as
"a" | "b". typeofandkeyofin type positions.- The earlier chapters of this tutorial: widening,
as conston objects, and deriving unions with(typeof X)[number].
The problem both features solve
Code often needs a closed set of named values, such as order statuses, log levels, or HTTP methods. You want three things:
- Readable names at the call site, such as
Status.Activeinstead of a bare"active". - A type that accepts only members of the set.
- Often, a runtime list of the members for validation or UI.
TypeScript offers two idioms for this. The enum keyword is a TypeScript feature that exists at runtime. The as const object is ordinary JavaScript plus a type derived from it.
What an enum is
A string enum declares a named set of string constants:
enum Direction {
Up = "UP",
Down = "DOWN",
}
function move(d: Direction): void {
console.log(`moving ${d}`);
}
move(Direction.Up);
// move("UP"); // error: Argument of type '"UP"' is not assignable to parameter of type 'Direction'.Direction is both a value (an object at runtime) and a type. The compiler does not erase it. It emits JavaScript that builds the object:
var Direction;
(function (Direction) {
Direction["Up"] = "UP";
Direction["Down"] = "DOWN";
})(Direction || (Direction = {}));Enums have properties that matter for the comparison:
- They are nominal-ish. A string enum type accepts only its own members. The plain literal
"UP"is rejected even though it has the same value, so callers must import the enum. - Enum values widen to their base type.
Direction.Upis assignable tostring, but not the other way around. - Numeric enums have reverse mappings.
enum Level { Low, High }produces an object whereLevel[0] === "Low"as well asLevel.Low === 0. - They are not plain type-level syntax. An enum generates code, so a tool that only deletes type annotations cannot handle it.
The as const object equivalent
The same set written with a const object looks like this:
const Direction = {
Up: "UP",
Down: "DOWN",
} as const;
type Direction = (typeof Direction)[keyof typeof Direction];
// "UP" | "DOWN"
function move(d: Direction): void {
console.log(`moving ${d}`);
}
move(Direction.Up); // OK
move("UP"); // OK: the type is just a union of string literals
// move("LEFT"); // error: Argument of type '"LEFT"' is not assignable to parameter of type 'Direction'.The value and the type share the name Direction. TypeScript keeps values and types in separate namespaces, so this is legal. Importing Direction brings in both.
The emitted JavaScript is just the object literal. as const and the type alias are erased:
const Direction = {
Up: "UP",
Down: "DOWN",
};Here the type is a union of ordinary string literals, so structural typing applies. Any "UP" string is accepted, whether it comes from a literal, a JSON payload that you validated, or another module that never imported Direction.
Side-by-side differences
| Aspect | `enum` | `as const` object |
|---|---|---|
| Emitted JavaScript | An IIFE that builds an object | The object literal you wrote |
| Works with type-stripping tools | No, it needs a code transform | Yes, only annotations are erased |
| Accepts a matching string literal | No (string enums) | Yes |
| Reverse mapping (value to name) | Built in for numeric enums | You build it yourself |
| Iterating with `Object.values` | Includes names for numeric enums | Returns exactly the values |
| Type is a union of literals | Yes, a union enum type | Yes, derived with `typeof` and `keyof` |
| Needs two declarations | One | Two (value and type), or one plus a helper |
| Can be a member-level type | `Direction.Up` is a type | Use `typeof Direction.Up` |
The last row matters in practice. With an enum you can write type UpOnly = Direction.Up. With the object you must write type UpOnly = typeof Direction.Up, which gives "UP".
Gotchas with enums
Numeric enums are loose
A numeric enum value is a number, and a plain number variable is still assignable to it:
enum Level {
Low,
High,
}
const n: number = 42;
const lvl: Level = n; // compiles, even though 42 is not a memberSince TypeScript 5.0, assigning an out-of-range numeric literal such as const bad: Level = 42 is an error, but a non-literal number still passes. A numeric as const object avoids the problem because its type is the literal union 0 | 1:
const Level = {
Low: 0,
High: 1,
} as const;
type Level = (typeof Level)[keyof typeof Level]; // 0 | 1
const n: number = 42;
// const lvl: Level = n; // error: Type 'number' is not assignable to type 'Level'.
const ok: Level = Level.High;Reverse mappings pollute iteration
Numeric enums store both directions in one object, so iterating returns names and numbers together:
enum Level {
Low,
High,
}
console.log(Object.values(Level)); // ["Low", "High", 0, 1]
console.log(Level[0]); // "Low"String enums do not have this problem, but you must remember which kind you have. A const object never mixes keys and values.
Enums need a code transform
Some runtimes can execute TypeScript by deleting type annotations, with no other rewriting. Node.js type stripping is one example. That approach cannot handle enums, because an enum must be turned into JavaScript. The compiler flag erasableSyntaxOnly (TypeScript 5.8) makes the compiler report enums and other non-erasable syntax as errors, so you find out at compile time. If your project runs TypeScript through such a tool, as const objects are the safe choice.
const enum has its own caveats
A const enum is inlined at each use site and leaves no object behind:
const enum Mode {
Read = "read",
Write = "write",
}
const m = Mode.Read; // emitted as: const m = "read" /* Mode.Read */;This is smaller at runtime, but it conflicts with tools that compile one file at a time. With isolatedModules, a compiler cannot inline a const enum declared in another file unless it can see that file. Libraries that ship const enum declarations in .d.ts files cause trouble for their consumers. A const object with as const is inlined by bundlers when they can, and works the same in every tool.
Gotchas with as const objects
You maintain two declarations
The value and the type are separate declarations. If you forget the type alias, Direction works as a value but not as a type, and you get the error 'Direction' refers to a value, but is being used as a type here. A common fix is to write the alias once as a generic helper:
type ValueOf<T> = T[keyof T];
const Direction = {
Up: "UP",
Down: "DOWN",
} as const;
type Direction = ValueOf<typeof Direction>; // "UP" | "DOWN"Nothing stops mutation at runtime
as const is compile-time only. The properties are readonly in the type, but the object is a normal mutable JavaScript object. Code that casts away readonly, or plain JavaScript code, can change it:
const Direction = {
Up: "UP",
Down: "DOWN",
} as const;
(Direction as { Up: string }).Up = "SIDEWAYS";
console.log(Direction.Up); // "SIDEWAYS"Enums behave much the same. TypeScript marks enum members read-only, but the emitted object is also an ordinary object. If you need real runtime protection, wrap the object in Object.freeze. In that case, keep as const as well, because Object.freeze alone infers wider types for nested values:
const Direction = Object.freeze({
Up: "UP",
Down: "DOWN",
} as const);
type Direction = (typeof Direction)[keyof typeof Direction]; // "UP" | "DOWN"Typos in plain strings are caught, but the names are not discoverable
Because "UP" is accepted anywhere, nothing forces callers to use Direction.Up. That makes the code more flexible, but it also lets the raw string spread through the code base. If you want to find every use of a member by searching for Direction.Up, enforce the convention with a lint rule or code review, or choose an enum.
Working with the values at runtime
A frequent need is turning an unknown string into the union type. Because the object holds exactly the values, validation is short:
const Status = {
Active: "active",
Archived: "archived",
} as const;
type Status = (typeof Status)[keyof typeof Status];
const STATUS_VALUES: readonly Status[] = Object.values(Status);
function isStatus(value: string): value is Status {
return (STATUS_VALUES as readonly string[]).includes(value);
}
function parseStatus(input: string): Status | undefined {
return isStatus(input) ? input : undefined;
}
console.log(parseStatus("active")); // "active"
console.log(parseStatus("deleted")); // undefinedObject.values returns Status[] here because every property type is a member of the union. The readonly string[] cast is needed for includes, whose parameter type would otherwise reject a plain string.
For enums the same code works when the enum is a string enum. For a numeric enum you must filter out the reverse-mapped names first, for example with typeof v === "number".
If you also need the key names, Object.keys(Status) returns string[], not a union of keys, because TypeScript cannot assume an object has no extra properties. Cast it when you know the shape:
const keys = Object.keys(Status) as (keyof typeof Status)[];
// ("Active" | "Archived")[]Mixed usage and migration
You can move between the two styles without changing call sites that use Status.Active. Moving from an enum to a const object has a few effects:
- Code that passes plain literals starts compiling where it was previously an error. This is rarely a problem.
- Code that uses enum members as types (
Direction.Upin a type position) must change totypeof Direction.Up. - Code that depends on reverse mapping (
Level[0]) must switch to an explicit lookup table. - Exported declarations in a public API change their emitted
.d.tsshape. Consumers that import the enum as a type keep working, because the alias has the same name.
Moving the other way, from a const object to an enum, makes the type stricter. Every place that passes a string literal then fails to compile.
How to choose
Prefer an as const object when:
- The values arrive from outside the program (JSON, database rows, query strings) and you want plain strings to flow into the type after validation.
- You want only erasable syntax, so any build tool or runtime that strips types works.
- You want
Object.valuesandObject.keysto return exactly what you wrote. - The set is shared across packages, and you do not want consumers to need your exact enum import to pass a value.
Prefer a string enum when:
- You want callers to be unable to pass an arbitrary string, as an opaque-token style guarantee.
- Members need to be usable as types by themselves (
Direction.Upas a type). - The code base already uses enums and consistency has more value than the change.
Avoid numeric enums for values that are stored or sent over a network. The numbers carry no meaning to a reader of the data, and the loose assignment rules let invalid numbers through. If you need numbers, use a numeric as const object, or use string values.
Whichever you pick, apply it consistently. A project that mixes both styles for the same kind of data forces every reader to learn two sets of rules.
Exercises
Exercise
A project uses Node.js type stripping to run .ts files directly, with no compile step. A teammate adds enum Role { Admin = "admin", User = "user" } and the program fails to start. Rewrite the declaration so it works, keeping both the value Role.Admin and the type Role.
Show answer
Enums need a code transform, which type stripping does not perform. Use a const object and a derived type:
const Role = { Admin: "admin", User: "user" } as const;
type Role = (typeof Role)[keyof typeof Role];
The emitted JavaScript is just the object literal, and as const plus the type alias are erased. Role is now usable as a value (Role.Admin) and as the type "admin" | "user".
Exercise
Given const Level = { Low: 0, High: 1 } as const; and type Level = (typeof Level)[keyof typeof Level];, what is the type Level, and does const x: Level = someNumber; compile when someNumber is declared const someNumber: number = 1?
Show answer
Level is the union 0 | 1. The assignment does not compile, because the type number is not assignable to 0 | 1. With a numeric enum Level { Low, High } the same assignment would compile, because a non-literal number is still assignable to a numeric enum type.
Exercise
Why does Object.values(Level) return ["Low", "High", 0, 1] for enum Level { Low, High }, and what does Object.values return for const Level = { Low: 0, High: 1 } as const?
Show answer
A numeric enum generates a reverse mapping, so the runtime object has both Level.Low === 0 and Level[0] === "Low", and Object.values lists names and numbers. The const object has only the two properties you wrote, so Object.values returns [0, 1], typed as (0 | 1)[].