Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
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
}
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'
}
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.
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
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.