Enum is basically a set of unique numeric values that we can represent by assigning friendly names to each one of them. The use of enums goes beyond assigning an alias to a number. We can use them as a way to list, in a convenient and recognizable way, the different variations that a specific type can assume.
Enums are declared using the enum keyword, without var or any other variable declaration noun, and they begin numbering members starting at 0 unless explicit numeric values are assigned to them:
enum Brands { Chevrolet, Cadillac, Ford, Buick, Chrysler, Dodge };
var myCar: Brands = Brands.Cadillac;
Inspecting the value of myCar will return 1 (which is the index held by Cadillac in the enum). As we mentioned already, we can assign custom numeric values in the enum:
enum BrandsReduced { Tesla = 1, GMC, Jeep };
var myTruck: BrandsReduced = BrandsReduced.GMC;
Inspecting myTruck will yield 2, since the first enumerated value was set as 1 already. We can extend value assignation to all the enum members as long as such values are integers:
enum StackingIndex {
None = 0,
Dropdown = 1000,
Overlay = 2000,
Modal = 3000
};
var mySelectBoxStacking: StackingIndex = LayerStackingIndex.Dropdown;
One last trick worth mentioning is the possibility to look up the enum member mapped to a given numeric value:
enum Brands { Chevrolet, Cadillac, Ford, Buick, Chrysler, Dodge };
var MyCarBrandName: string = Brands[1];
It should be mentioned that from TypeScript 2.4 it is possible to assign string values to Enums.