TypeScript Enum



Enums allow us to define or declare a collection of related values that can be numbers or strings as a set of named constants.


Enums are a TypeScript data type that allows the organization of number-based collections of unique identifiers.

Create Enum in TypeScript

In typescript, enums can be created by using the “enum” keyword. By default enums are assign numeric values starting with 0;


Here’s define the simple examples of enum in TypeScript:


Example 1:

enum Countries {
    India,
    Srilanka,
    AUS,
    England,
  }
console.log(Countries)

//Output:

{ '0': 'India',
  '1': 'Srilanka',
  '2': 'AUS',
  '3': 'England',
  India: 0,
  Srilanka: 1,
  AUS: 2,
  England: 3 }

Example 2: Following example shows how to get particular enum value in typescript:

enum Countries {
    India,
    Srilanka,
    AUS,
    England,
  }

let objCountries = Countries.India;
console.log(" Value of India is: "+objCountries);

//output:
Value of India is: 0

We can access an enum value by its number value or by the string that is associated with it.


Example:

enum Countries {
    India,
    Srilanka,
    AUS,
    England,
  }
console.log(" Value of India is: "+ Countries['India']);
console.log(" Value of Srilanka is: "+ Countries['Srilanka']);
console.log(" Value of AUS is: "+ Countries['AUS']);
console.log(" Value of England is: "+ Countries['England']);
console.log(" string of Zero value is: "+ Countries[0]);
console.log(" string of One value is: "+ Countries[1]);
console.log(" string of Two value is: "+ Countries[2]);
console.log(" string of Three value is: "+ Countries[3]);

//output:
Value of India is: 0
 Value of Srilanka is: 1
 Value of AUS is: 2
 Value of England is: 3
 string of Zero value is: India
 string of One value is: Srilanka
 string of Two value is: AUS
 string of Three value is: England

Enums are zero-based, but we can change that by setting a number value of your choice on the first item. Here, for example, our enum will have an index that starts with 1:


Example:

enum Countries {
    India =1,
    Srilanka,
    AUS,
    England,
  }
console.log(" Value of India is: "+ Countries['India']);
console.log(" Value of Srilanka is: "+ Countries['Srilanka']);
console.log(" Value of AUS is: "+ Countries['AUS']);
console.log(" Value of England is: "+ Countries['England']);

//OUTPUT:
Value of India is: 1
Value of Srilanka is: 2
Value of AUS is: 3
Value of England is: 4

Here another example for typescript enum, we can skip to new values, and the next values will follow:

enum Countries {
    India =1,//New Value
    Srilanka,
    AUS=10, //New Value
    England,
  }
console.log(" Value of India is: "+ Countries.India);
console.log(" Value of Srilanka is: "+ Countries.Srilanka);
console.log(" Value of AUS is: "+ Countries.AUS);
console.log(" Value of England is: "+ Countries.England);

//output:
Value of India is: 1
Value of Srilanka is: 2
Value of AUS is: 10
Value of England is: 11


Types of enums in TypeScript

In simple words, enums allow us to declare a set of named constants. There are three types of enums in typescript:

  • Numeric enum

  • String enum

  • Heterogeneous enum


Numeric enum in typescript

Numeric enums are number-based enums i.e. they store string values as numbers.


Example:

enum ITCompanies {
    Wipro,
    Infosys,
    TSInfo,
  }
  console.log(" Value of TSInfo is: "+ITCompanies.TSInfo)

//output:
Value of TSInfo is: 2


String enum in typescript

String enums in typescript are similar to numeric enums, except that the enum values are initialized with string values rather than numeric values.


Difference between numeric and string enums is that numeric enum values are auto-incremented, while string enum values need to be individually initialized.


The benefits of using string enums is that string enums offer better readability. If we were to debug a program, it is easier to read string values rather than numeric values.


Example:

enum Employees{
    Name = 'lakshmi',
    company='TSInfo'
}  
console.log(Employees)
console.log(Employees.Name)

//output:
{ Name: 'lakshmi', company: 'TSInfo' }
lakshmi


Heterogeneous enums in typescript

Heterogeneous enums in typescript are enums that contain both string and numeric values.


Example:

enum Employees{
    Name = 'lakshmi',
    company='TSInfo',
    EmpID = 777
}  
console.log(Employees)
console.log(Employees.EmpID)

//output:
{ '777': 'EmpID', Name: 'lakshmi', company: 'TSInfo', EmpID: 777 }
777

Typescript compile the above code into JavaScript:

var Employees;
(function (Employees) {
    Employees["Name"] = "lakshmi";
    Employees["company"] = "TSInfo";
    Employees[Employees["EmpID"] = 777] = "EmpID";
})(Employees || (Employees = {}));
console.log(Employees);
console.log(Employees.EmpID);


Reverse Mapping of Enum in TypeScript

Reverse mapping means we can access the value of a member and also a member name from its value.


Example: Below an example of reverse mapping from typescript enum values to enum names.

enum ITCompanies {
        Wipro,
        Infosys,
        TSInfo,
      }

let objITCompanies = ITCompanies.TSInfo;
let nameofTSInfo = ITCompanies[objITCompanies];//reverse mapping
console.log(nameofTSInfo);

//output:
TSInfo


Const Enum in TypeScript

To avoid paying the cost of extra generated code and additional indirection when accessing enum values, it’s possible to use const enums. Define the const enums in typescript as like below:


Syntax:

Const enum enumName{}


Example 1:

enum ITCompanies {
        Wipro,
        Infosys,
        TSInfo,
      }
var objITComp = ITCompanies.TSInfo;

The line var objITComp = ITCompanies.TSInfo; is compiled to the JavaScript var objITComp = ITCompanies.TSInfo; (this output is the same as input). This means that at execution the runtime will need to lookup “ITCompanies” and then “ITCompanies.TSInfo”.


To get a performance boost here you can mark the enum as a “const enum“. This is demonstrated below:

const enum ITCompanies {
        Wipro,
        Infosys,
        TSInfo,
      }
var objITComp = ITCompanies.TSInfo;
console.log(objITComp);

Const enums can only use constant enum expressions and unlike regular enums, they are completely removed during compilation.


Above example generated the javascript:

var objITComp = 2 /* TSInfo */;
console.log(objITComp);


Enum switch in TypeScript

let’s see simple example,how to work with switch enum in typescript:

const enum ITCompanies {
    Wipro,
    Infosys,
    TSInfo,
  }

function getCompanies(CompDetails: ITCompanies) {  
    switch (CompDetails) { 
        case ITCompanies.Wipro:
            return `Wipro operates in over 50 countries `;
        case ITCompanies.Infosys:
            return 'Infosys operates in over 30 countries';
         case ITCompanies.TSInfo:
            return 'TSinfo operates in over 10 countries';
        default:
            throw new Error('unreachable case');
    } 
}
const objWipro = ITCompanies.Wipro;
console.log(getCompanies(objWipro))


//output:
Wipro operates in over 50 countries


Computed Enums in TypeScript

The value of a numeric enum can either be constant or evaluated, just like any other numeric data type in TypeScript. You can define or initialize your numeric enum with a computed value:


Example:

enum Year {
    Jan,
    Feb = getValue('Feb'),
    Apr = Feb *15
  }
  
  function getValue(month : string): number {
      if (month === 'Feb') {
          return 2;
      }
  }
  console.log(Year.Feb); 
  console.log(Year.Apr); 

//output:
2
30

Enum with static functions

You can use the declaration “enum + namespace” merging to add static methods to an enum in typescript. The following demonstrates an example where we add a static member getMonth to an enum Year:

enum Year {
   Jan,
   Feb,
   Mar,
}
namespace Year {
    export function getMonth(months: Year) {
        switch (months) {
            case Year.Jan:
                return true;
            case Year.Feb:
                return false;
            default:
                return 'unreachable';
        }
    }
}

const obj = Year.Mar;
console.log(Year.getMonth(obj));
//output:
unreachable

Hope this typescript tutorial helps to learn typescript enum in details. How to create an enum in typescript.


We also discussed on TypeScript enum types, reverse mapping of enum in typescript, Const Enum in TypeScript, Enum switch in TypeScript, Computed Enums in TypeScript, Enum with static functions.



Source: SP Guide


The Tech Platform

www.thetechplatform.com

0 comments

Recent Posts

See All