Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

typescript

Typescript enum complete guide

This article discusses how to create an enum with or without value and access those value, merge and how add a function to an enum

typescript enum is mainly used to specify the one or few possible values which can be used in your application. Let’s say if we want to define a set of priority types which can be used in the application you can use an enum.

enum can be defined with or without value.

enum without value

If we create an enum without specifying the value it will default assign a value which starts from 0.

enum Priorities{
  LOW,
  MEDIUM,
  HIGH
}

in here if we check value of Priorities.MEDIUM it will be 1.

in case if we explicitly assigned a value to one of the enum properties, it will change the value of the field after that

enum Priorities2{
  LOW,
  MEDIUM = 5,
  HIGH 
}
Priorities2.HIGH //print value 6

enum with value

Also if we need to associate a value with the enum we can do that also like below

enum Priorities{
  LOW = "Low",
  MEDIUM = "Medium",
  HIGH = "High"
}

In this scenario, if we access the Priorities.MEDIUM the value will be Medium

Different ways to access enum

You can use dot notation to access enum value. Or you can access it like accessing a object.

enum Priorities{
  LOW = "Low",
  MEDIUM = "Medium",
  HIGH = "High"
}

console.log(Priorities.HIGH) 
console.log(Priorities['LOW']) 

If you have has a numeric value you can use value to get the name. But it cannot be done if you have a string value

enum Priorities2{
  LOW,
  MEDIUM = 5,
  HIGH 
}

console.log(Priorities2[0]) // LOW

console.log(Priorities2[5]) // MEDIUM

Merge enum

if you define two enums with the same name and different values those will be merged in to one automatically.

enum Priorities{

  HIGHER = "Higher"
}

enum Priorities{
  LOW = "Low",
  MEDIUM = "Medium",
  HIGH = "High"
}

console.log(Priorities.HIGHER) //print Higher

Add function to enum

You can also add a function to an enum.

enum Priorities{
  LOW = "Low",
  MEDIUM = "Medium",
  HIGH = "High",
}

namespace Priorities {
    export function printPriority() {
        console.log("Hi Priority");
    }
}

console.log(Priorities.printPriority())