TypeScript - Enums
An enum is a special "class" that represents a group of constants (unchangeable variables).
Numeric Enums - Default
By default, enums will initialize the first value to 0
and add 1 to each additional value:
enum Directions { North, East, South, West }
let currentDirection = Directions.North;
console.log(currentDirection); // 0
currentDirection = 'North'; // throws error as 'North' is not a valid enum
Numeric Enums - Initialized
You can set the value of the first numeric enum and have it auto increment from that:
enum Directions { North = 1, East, South, West }
console.log(Directions.North); // 1
console.log(Directions.West); // 4
Numeric Enums - Fully Initialized
You can assign unique number values for each enum value. Then the values will not incremented automatically:
enum StatusCodes {
NotFound = 404,
Success = 200,
Accepted = 202,
BadRequest = 400
}
console.log(StatusCodes.NotFound); // 404
console.log(StatusCodes.Success); // 200
String Enums
Enums can also contain strings
. This is more common than numeric enums, because of their readability and intent.
enum CardinalDirections {
North = 'North',
East = "East",
South = "South",
West = "West"
};
console.log(CardinalDirections.North); // "North"
console.log(CardinalDirections.West); // "West"