In Typescript, an enum (enumeration) is a way to create a named set of named constant values.
Enums allow us to define a set of related named constants, making our code more readable and self-explanatory.
Enums are helpful when we have a set of values that are related and known at compile time.
Enum Support Reverse Mapping: Enums support reverse mapping, we can access the enum member attribute from its value.
Assign Auto Numbering: By default, Enums are automatically assigned numeric values starting from 0. We can also assign specific string values or numeric values to enum members.
Support Named Constants: Enums allow us to define a set of named constants that can be easily referenced throughout our code.
Numeric enums are enums where each member has an associated numeric value.
enum Direction { UP, // 0 DOWN, // 1 LEFT, // 2 RIGHT // 3 } let arrowButtonPress: Direction = Direction.RIGHT; console.log(arrowButtonPress); // Output: 3
Direction is an enum with default numeric values starting from 0. we can explicitly set values as well.
enum Permission { ADMIN = "Admin", SUPER_ADMIN = "Super Admin", IAM = "Iam" } let selectedPermission: Permission = Permission.ADMIN; console.log(selectedPermission); // Output: "Admin"
String enums are enums where each member has an associated string value.
Permission is an enum with string values assigned to each member.
enum Months { JAN = 1, FEB = "feb", MAR = "mar", APR = "apr", MAY = 5, JUNE = 6 } let selectedMonth: Months = Months.APR; console.log(selectedMonth); // Output: "apr"
enum StatusCode { OK = 200, BadRequest = 400, NotFound = 404, InternalServerError = 500 } let responseCode: StatusCode = StatusCode.OK; console.log(responseCode); // Output: 200
Heterogeneous enums allow a mix of string and numeric values.
enum Months { JAN = 1, FEB = "feb", MAR = "mar", APR = "apr", MAY = 5, JUNE = 6 } let month: string = Months[0]; // Accessing enum value by numeric value console.log(month); // Output: 1 enum StatusCode { OK = 200, BadRequest = 400, NotFound = 404, InternalServerError = 500 } let statusCode: string = StatusCode["OK"]; // Accessing enum value by string value console.log(statusCode); // Output: 200
We can explicitly set numeric values for each member.
We can access the values of an enum using the enum name and the member name.