Enums
Special classes representing groups of constants
Numeric enums; default
By default, enums are numeric, starting at 0, and incrementing by 1
enum Compass {
North,
East,
South,
West,
}
let currentDirection = Compass.North;
console.log(currentDirection); // North is the first value
// so it logs '0'
currentDirection = 'North'; // Error: "North" is not assignable
// to type 'Compass'.
Numeric enums done right, initialized
enum Compass2 {
North = 1,
East,
South,
West,
}
console.log(Compass2.North); // logs 1
console.log(Compass2.South); // logs 3
Initialized numeric enums fully set up
enum LeetCodes {
E = 3,
T = 7,
S = 5,
A = 4,
}
console.log(LeetCodes.E); // logs 3
console.log(LeetCodes.A); // logs 4
String enums
enum Compass3 {
North = 'North',
East = 'East',
South = 'South',
West = 'West',
}
console.log(Compass3.North); // logs "North"
console.log(Compass3.South); // logs "South"