
TypeScript Enums
By default, enums will initialize the first value to 0 and add 1 to each additional value:
Example: enum CardinalDirections { North, East, South, West }; let currentDirection = CardinalDirections.North; console.log(currentDirection); // Output:0
You can set the value of the first numeric enum and have it auto increment from that:
Example: enum CardinalDirections { North = 1, East, South, West }; console.log(CardinalDirections.North); console.log(CardinalDirections.West); //Output :1 //Output: 4
You can assign unique number values for each enum value. Then the values will not incremented automatically:
Example:
enum StatusCodes {
NotFound = 404,
Success = 200,
Accepted = 202,
BadRequest = 400
};
console.log(StatusCodes.NotFound);
console.log(StatusCodes.Success);
//Output:404
//Output:200
Enums can also contain strings This is more common than numeric enums, because of their readability and intent.
Example: enum CardinalDirections { North = 'North', East = "East", South = "South", West = "West" }; console.log(CardinalDirections.North); console.log(CardinalDirections.West); //Output:North //output:West