What is an enum in TypeScript
What is an enum?
An enum (enumeration) in TypeScript is a way to define a set of named constants. It makes code easier to read and prevents scattering “magic” strings or numbers throughout your project.
enum Status {
Pending,
InProgress,
Done
}
Numeric vs string enums
By default enums are numeric: the first item gets value 0, and each next member is incremented by 1. You can override the starting value or set explicit numbers.
enum Status {
Pending = 1,
InProgress = 3,
Done = 4
}
String enums must be assigned explicitly:
enum Role {
Admin = 'admin',
User = 'user'
}
Reverse mapping
For numeric enums the emitted JavaScript object has reverse mapping. That means you can get the enum name from its numeric value:
enum Status {
Pending,
Done
}
Status.Pending // 0
Status[0] // 'Pending'
String enums do not have reverse mapping.
const enum
Using const enum tells the compiler to inline the values and skip generating an object at runtime. This reduces bundle size but eliminates reverse mapping.
const enum Directions {
Up,
Down
}
const move = Directions.Up // will be compiled to the literal 0
When to use enums
- When you have a fixed list of states (statuses, roles, message types).
- When the same set of values is used in multiple places.
- When you want cleaner, self-documenting APIs instead of ad-hoc strings/numbers.
Interview tip:
Mention that enums are sugar over objects, describe the difference between numeric and string enums, and don’t forget about const enum for optimization.