Enums
What are enums?
Enums (short for enumerations) allow you to define a set of named constants. They are useful when a value must be one of a limited set of options, such as statuses, roles, or categories. Enums improve readability and reduce the use of unclear "magic values" in production code.
Numeric enums
By default, TypeScript enums are numeric. Each member is assigned an incrementing number.
enum Status {
Draft,
Published,
Archived
}
let postStatus: Status = Status.Draft;
Here, Draft = 0, Published = 1, and Archived = 2 unless explicitly assigned.
Custom numeric values
You can assign explicit numeric values to enum members.
enum Role {
Admin = 1,
Editor = 2,
User = 3
}
This is useful when matching database values or API codes.
String enums
String enums are often preferred in production because they are more readable at runtime.
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT"
}
String enums avoid ambiguity and are easier to debug.
Enums in conditional logic
Enums work well with switch statements and conditional branching.
function handleStatus(status: Status) {
switch (status) {
case Status.Draft:
return "Editing mode";
case Status.Published:
return "Live";
case Status.Archived:
return "Hidden";
}
}
Using enums ensures that only valid states are handled.
Const enums
Const enums are removed during compilation and inlined for better performance. However, they should be used carefully, especially in shared libraries.
const enum Priority {
Low,
Medium,
High
}
Enum alternatives
In modern TypeScript, union literal types often replace enums for simpler cases.
type Status = "draft" | "published" | "archived";
Union types provide similar safety with less runtime overhead.
When to use enums
- When values map to numeric codes or database identifiers.
- When runtime representation matters.
- When grouping related constants improves clarity.
When to avoid enums
- For simple string-based state management where union types are cleaner.
- When tree-shaking and minimal runtime output are priorities.
Production guidance
- Prefer string enums for better runtime readability.
- Use const enums carefully in performance-sensitive code.
- Consider union types for lightweight scenarios.
- Avoid mixing enum types with raw values.
What’s next
Now that you understand enums, the next step is creating reusable type definitions using type aliases and interfaces.