Sub topic 9
`as const` Objects or Enums
Assume you know basic TypeScript object types, union types, typeof, and keyof. This chapter compares two ways to represent a fixed set of named values: a plain object with as const and a TypeScript enum.
Both approaches can represent values such as user roles or order states. They differ in runtime behavior, generated JavaScript, type inference, and how easily they work with ordinary JavaScript tools.
The `as const` object pattern
An as const object is an ordinary JavaScript object whose properties keep their literal types and become readonly:
const Status = {
Active: "active",
Archived: "archived",
} as const;
type Status = (typeof Status)[keyof typeof Status];
const current: Status = Status.Active;
console.log(current); // activeThe object has two related uses:
Status.Activeis a runtime value.Statusis a type containing"active" | "archived".
The indexed-access expression creates the union:
typeof Statusgets the object type.keyof typeof Statusgets the keys"Active" | "Archived".(typeof Status)[keyof typeof Status]gets the values"active" | "archived".
The value and type intentionally share the name Status. TypeScript keeps value names and type names in separate namespaces, so this is valid.
You can also define the keys and values differently:
const HttpStatus = {
ok: 200,
notFound: 404,
serverError: 500,
} as const;
type HttpStatusCode =
(typeof HttpStatus)[keyof typeof HttpStatus];
function isError(code: HttpStatusCode): boolean {
return code >= 400;
}
console.log(isError(HttpStatus.notFound)); // trueThe resulting type is 200 | 404 | 500, not just number.
The equivalent enum
An enum is a TypeScript declaration that creates a named set of constants:
enum StatusEnum {
Active = "active",
Archived = "archived",
}
const current: StatusEnum = StatusEnum.Active;
console.log(current); // activeThe enum type is StatusEnum, and its runtime object is also named StatusEnum. You do not need a separate indexed-access type.
For string values, the two approaches provide similar application code:
const objectStatus = Status.Active;
const enumStatus = StatusEnum.Active;However, they are not the same type. A value of type Status is not automatically a value of type StatusEnum, even when both contain the same strings.
Important differences
| Concern | `as const` object | `enum` |
|---|---|---|
| Runtime representation | Plain JavaScript object | Enum object generated by TypeScript |
| Derived value union | Requires `typeof` and indexed access | Built in as the enum type |
| JavaScript interoperability | Excellent | Requires enum-aware TypeScript usage |
| Tree-shaking | Usually straightforward | Depends on emitted code and tooling |
| Numeric reverse mapping | No | Available for numeric enums |
| Mutation protection | Compile-time readonly only | Members cannot be reassigned through the enum type |
| Runtime validation | Must write it separately | Still must write it separately |
A plain object often fits libraries, configuration, API clients, and code shared with JavaScript. It produces familiar JavaScript and works naturally with Object.values, serialization, and JSON.
An enum can be useful when the named type itself is central to a TypeScript-only codebase. It gives the set a dedicated declaration and can make some APIs easier to read.
Runtime and emitted-code trade-offs
An as const assertion disappears during compilation:
const Role = {
Admin: "admin",
Viewer: "viewer",
} as const;The emitted JavaScript is essentially the same object:
const Role = {
Admin: "admin",
Viewer: "viewer",
};A regular enum generates runtime code. A string enum is commonly emitted as an object:
var StatusEnum;
(function (StatusEnum) {
StatusEnum["Active"] = "active";
StatusEnum["Archived"] = "archived";
})(StatusEnum || (StatusEnum = {}));Numeric enums also support reverse lookup:
enum Direction {
Up,
Down,
}
console.log(Direction.Up); // 0
console.log(Direction[0]); // UpThis reverse mapping can be useful, but it also adds runtime behavior and can make numeric enums less predictable when numbers cross API boundaries. String enums are generally safer for serialized data because their values remain readable.
Choosing between them
Prefer an as const object when:
- Values cross a JSON or JavaScript boundary.
- You want one runtime object to derive a union type.
- You want simple emitted JavaScript.
- You need ordinary object operations such as
Object.keysorObject.values. - Your project avoids enums for bundle or tooling reasons.
Prefer an enum when:
- The project already uses enums consistently.
- A dedicated named TypeScript type improves the public API.
- Enum-specific behavior, such as numeric reverse mapping, is useful.
- The values are primarily internal to TypeScript code.
For external data, neither option validates untrusted input by itself. A value received from a request is still just runtime data. Check it before treating it as a valid role or status.
const Role = {
Admin: "admin",
Viewer: "viewer",
} as const;
type Role = (typeof Role)[keyof typeof Role];
function isRole(value: string): value is Role {
return Object.values(Role).includes(value as Role);
}
const input: string = "admin";
if (isRole(input)) {
console.log(`Known role: ${input}`);
}The type predicate value is Role tells TypeScript that the value has been checked inside the if block.
Exercise
You need a list of API methods, want the union type "GET" | "POST", and want the emitted JavaScript to remain a simple array. Which pattern should you choose, and why?
Show answer
Choose an as const array. It keeps the array as a readonly tuple, and (typeof methods)[number] derives the literal union without generating enum runtime code.