Enum In Typescript

Introduction

 
In this article you will learn about Enum in Typescript in detail. This article will help beginners to understand the concept.
 

What is Enum? 

  • The short form of enumeration is enum.
  • It is used as a type with some set of values called a named constant.
  • Inernally it holds numeric type values or in some cases we can create heterogeneous enums.
  • The enum keyword is used to define the enums.
  • We can create a distinct case so it makes it easy to document.
  • It forces us to use all possible values.
  • Access the enums using index or use dot operator after the enum name & named constant.
  • Initial value starts from 0 if we do not set any value.
  • Auto incremental is the best approach to use because we do not need to worry about the values.
Syntax
  1. enum enumName{  
  2. constant1, constant2, constant3...  
  3. }  
Example 
 
Consider  traffic signal lights as an example.
 
 
We can access the elements using index or by constant name:
  1. enum signalLights{  
  2.    red, yellow, green  
  3. }  
  4. let result: string = signalLights[signalLights.red];  
  5. console.log(result);  
  6. console.log(signalLights[1]);  
  7. let output: signalLights = (<any>signalLights)["yellow"];  
  8. console.log(output);  
Output
 
red
yellow
1
 

Types of enums

 

Numeric enum

  • It is commonly used in all languages.
  • Initial value starts from 0 if we do not set any value.
  • Takes only numeric values.
  • enum keyword is used to declare the numeric type enum.
  • We can assign any value as per our requirements.
  • If our function returns any numeric value then we can use this function to initialize the constant.
Consider that in the below rainbowColors is enum & we have not initialized any constants, so it will starts with 0 value and the rest of the constants have auto increamemtal values.
 
Example 
  1. enum rainbowColors {  
  2.     Red,  
  3.     Orange,  
  4.     Yellow,  
  5.     Green,  
  6.     Blue,  
  7.     Indigo,  
  8.     Violet,  
  9. }  
  10. console.log("color & index value is as follows");  
  11. for (let item in rainbowColors) {  
  12.     if (isNaN(Number(item))) {  
  13.         console.log(item + " : " + < rainbowColors > rainbowColors[item]);  
  14.     }  
  15. }   
Output
 
color & index value is as follows:
 
Red : 0
Orange : 1
Yellow : 2
Green : 3
Blue : 4
Indigo : 5
Violet : 6
 
Consider the below example, rainbowColors is enum & the second element is initialized with value 1000. So it will be auto incremental to the  remaining constants. It will print on the console.
 
Example 
  1. enum rainbowColors {  
  2.     Red,  
  3.     Orange = 1000,  
  4.     Yellow,  
  5.     Green,  
  6.     Blue,  
  7.     Indigo,  
  8.     Violet,  
  9. }  
  10. console.log("color & index value is as follows");  
  11. for (let item in rainbowColors) {  
  12.     if (isNaN(Number(item))) {  
  13.         console.log(item + " : " + < rainbowColors > rainbowColors[item]);  
  14.     }  
  15. }   
Output
 
color & index value is as follows,
 
Red : 0
Orange : 1000
Yellow : 1001
Green : 1002
Blue : 1003
Indigo : 1004
Violet : 1005
 

Using function in enum

 
Consider the below example. We can use function in enum if we are returning the value from the function. It is used when the user needs to do any calculation. Suppose we need to calculate the total minutes like 1 hour = 60 minute, 2 hour = 120 minute, then it will create one function which will do a calcuation & return values to enum constant:
 
Example
  1. function Totalminute(hr: number): any{  
  2. return 60 * hr;  
  3. }  
  4. enum hours  
  5. {  
  6. One = Totalminute(1) ,  
  7. Two = Totalminute(2),  
  8. Three = Totalminute(4),  
  9. }  
  10. console.log(hours.One);  
  11. console.log(hours.Two);  
  12. console.log(hours.Three);  
Output
 
60
120
240
 

String enum

 
It is same as the numeric enums,  we are just passing string values/literals to our enum constant. enum keyword is used to declare the enums.
 
Consider the below example, our vehicle is taking different kinds of turns, and we will define the enum as:
 
Example
  1. enum vehicleTurn {  
  2.     Left = "Left",  
  3.         Right = "Right",  
  4.         UTurn = "UTurn"  
  5. }  
  6. console.log(vehicleTurn.Left);  
  7. console.log(vehicleTurn.Right);  
  8. console.log(vehicleTurn.UTurn);  
  9. }   
Output
 
Left
Right
UTurn
 

Heterogeneous enums

 
Typescript allows us to create a mixed type of enums.
 
This means we can assign numeric & string type values to enum.
 
Consider the below example, circleInfo has heterogeneous enum values.
 
Example
  1. enum circleInfo {  
  2.     Area = "area of circle",  
  3.         Pie = 3.112,  
  4.         Radius = 20  
  5. }  
  6. let result = circleInfo.Pie * circleInfo.Radius * circleInfo.Radius;  
  7. console.log(circleInfo.Area + " is :" + result);   
Output
 
area of circle is :1244.8
 

Point A - Function & interface using enum

 
Consider the below example, clothSize is enum which contains some constants. IClothSize is an interface which contains two properties, key & value, having string & number type respectively.
 
Function is taking enum as a parameter & will print the data on the console.
 
Example
  1. enum clothSize {  
  2.     small,  
  3.     medium,  
  4.     large  
  5. }  
  6. interface IClothSize {  
  7.     key: string,  
  8.         value: number  
  9. }  
  10.   
  11. function getClothSize(size: clothSize): IClothSize {  
  12.     switch (size) {  
  13.         case clothSize.small:  
  14.             return {  
  15.                 key: clothSize[clothSize.small], value: 10  
  16.             };  
  17.         case clothSize.medium:  
  18.             return {  
  19.                 key: clothSize[clothSize.medium], value: 20  
  20.             };  
  21.         case clothSize.large:  
  22.             return {  
  23.                 key: clothSize[clothSize.large], value: 30  
  24.             };  
  25.     }  
  26. }  
  27. console.log("cloth is " + getClothSize(clothSize.small).key + " & value is " + getClothSize(clothSize.small).value);  
  28. console.log("cloth is " + getClothSize(clothSize.medium).key + " & value is " + getClothSize(clothSize.medium).value);   
Output
 
cloth is small & value is 10
cloth is medium & value is 20
 

Point B - const enum

  • Typescript allows us to declare const enum.
  • const keyword is used.
  • It has a inlined values.
  • We can access enum using enum['ConstantName']
Example
  1. const enum myColor {  
  2.     Red = 10,  
  3.         White = Red * 4,  
  4.         Blue = White + 10,  
  5.         Yellow,  
  6. }  
  7. console.log(myColor.Red)  
  8. console.log(myColor.White)  
  9. console.log(myColor.Blue)  
  10. console.log(myColor['Yellow'])   
Output
 
10
40
50
51
 
We will not be able to access enum using index in const enum like myColor[0], it will give us an error.
 

Point C

 
ES6 allows us to use map enum keys.
 
Example
  1. enum classes {  
  2.     I,  
  3.     II,  
  4.     III,  
  5.     IV,  
  6.     V  
  7. }  
  8. const ClassNames = new Map < number,  
  9.     string > ([  
  10.         [classes.I, '100'],  
  11.         [classes.II, '200'],  
  12.         [classes.III, '300'],  
  13.     ]);  
  14. console.log(ClassNames);   
Output
 
Map(3) {0 => "100", 1 => "200", 2 => "300"}
 
We will modify the above example, we can use this into a classes as below.
 
Note
User can modify the code as per their requirement.
 
Example
  1. enum classes {  
  2.     I,  
  3.     II,  
  4.     III,  
  5.     IV,  
  6.     V  
  7. }  
  8. const ClassNames = new Map < number,  
  9.     string > ([  
  10.         [classes.I, '100'],  
  11.         [classes.II, '200'],  
  12.         [classes.III, '300'],  
  13.     ]);  
  14. class AllStandards {  
  15.     public allNames: object;  
  16.     constructor() {  
  17.         this.allNames = ClassNames;  
  18.     }  
  19. }  
  20. let obj: AllStandards = new AllStandards();  
  21. console.log(obj.allNames);   
Output
 
Map(3) {0 => "100", 1 => "200", 2 => "300"}
 

Point D - export enum

  • typescript allows us to export the enum.
  • export keyword is used before the enum.
  • import is used to import that enum file.
We can declare the enum like this: 
  1. export enum sportActivities {Football, Cricket,Badminton, Tennis}  
To import the enum in .ts,  i.e.; typescript file looks like this: 
  1. import {sportActivities} from '../enums'  

Summary

 
In this article, you learned about enum in Typescript.