☰ See All Chapters |
TypeScript enum type
An enum type is used to define one or more values for one type. Enum stands for Enumerations. Enums are defined by using the enum keyword. Each value defined in enum is a named constant. To define an enumerated type, the enum keyword must be followed by a name for the type and each of its possible values. This is shown in the following format:
enum nameOfEnum { value1, value2, value3, ... } |
Example:
enum Colour {RED, GREEN, BLUE}; |
When this is compiled into javascript, the result will contain the following code:
var Colour; (function (Colour) { Colour[Colour["RED"] = 0] = "RED"; Colour[Colour["GREEN"] = 1] = "GREEN"; Colour[Colour["BLUE"] = 2] = "BLUE"; })(Colour || (Colour = {})); ; |
As shown, the compiler assigns a number to each value of the enumerated type. These numeric values can be set in code, as shown in the below declaration. Number can be in any format octal, hexadecimal, binary, integer and floating.
enum Colour {RED = 0xFF0000 , GREEN = 0x008000, BLUE = 0x0000FF}; |
When assigning a variable to a value of an enumerated type, the value must be given using dot notation.
let col: Colour = Colour.RED; |
Types of Enums
We assign either numeric or string value to each value in enumerated type. Based on the values assigned we can create three types of enum:
Numeric Enums: Each value in enum is assigned with numeric values
String Enums: Each value in enum is assigned with string values
Heterogeneous Enums: Each value in enum is assigned with mix of numeric and string values
Numeric Enums
Each value in enum is assigned with numeric values in numeric enums.
enum Colour {RED = 0xFF0000 , GREEN = 0x008000, BLUE = 0x0000FF}; |
If we don’t assign values, typescript compiler assigns number to each value starting from 0. As shown below, the compiler assigns a number to each value of the enumerated type.
enum Colour {RED, GREEN, BLUE}; |
When this is compiled into javascript, the result will contain the following code:
var Colour; (function (Colour) { Colour[Colour["RED"] = 0] = "RED"; Colour[Colour["GREEN"] = 1] = "GREEN"; Colour[Colour["BLUE"] = 2] = "BLUE"; })(Colour || (Colour = {})); ; |
String Enums
Each value in enum is assigned with string values in string enums.
enum Colour {RED = 'RED', GREEN = 'GREEN', BLUE = 'BLUE'}; |
When this is compiled into javascript we get the javascript as below:
var Colour; (function (Colour) { Colour["RED"] = "RED"; Colour["GREEN"] = "GREEN"; Colour["BLUE"] = "BLUE"; })(Colour || (Colour = {})); ; |
Heterogeneous Enums
Each value in enum is assigned with mix of numeric and string values in Heterogeneous Enums.
enum Colour {RED = 'RED', GREEN = 0x008000, BLUE = 'BLUE'}; |
When this is compiled into javascript we get the javascript as below:
var Colour; (function (Colour) { Colour["RED"] = "RED"; Colour[Colour["GREEN"] = 32768] = "GREEN"; Colour["BLUE"] = "BLUE"; })(Colour || (Colour = {})); ; |
All Chapters