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.
  • Internally 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 an index or use the dot operator after the enum name & named constant.
  • The 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

enum enumName {
  constant1,
  constant2,
  constant3,
  // ...
}

Example

Consider traffic signal lights as an example.

We can access the elements using an index or by constant name:

enum signalLights {
  red,
  yellow,
  green
}
let result: string = signalLights[signalLights.red];
console.log(result);
console.log(signalLights[1]);
let output: signalLights = (<any>signalLights)["yellow"];
console.log(output);

Output

Output

Types of enums


Numeric enum

  • It is commonly used in all languages.
  • The 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 rainbow colors is an enum & we have not initialized any constants, so it will start with a 0 value and the rest of the constants have auto incremental values.

Example

enum rainbowColors {
  Red,
  Orange,
  Yellow,
  Green,
  Blue,
  Indigo,
  Violet,
}
console.log("color & index value is as follows");
for (let item in rainbowColors) {
  if (isNaN(Number(item))) {
    console.log(item + " : " + <rainbowColors>rainbowColors[item]);
  }
}

Output

Output

Consider the below example, rainbowColors is an enum & the second element is initialized with the value 1000. So it will be auto-incremental to the remaining constants. It will print on the console.

Example

enum rainbowColors {
  Red,
  Orange = 1000,
  Yellow,
  Green,
  Blue,
  Indigo,
  Violet,
}
console.log("color & index value is as follows");
for (let item in rainbowColors) {
  if (isNaN(Number(item))) {
    console.log(item + " : " + <rainbowColors>rainbowColors[item]);
  }
}

Output

Color index

Using function in enum

Consider the below example. We can use the function in an 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 minutes, 2 hours = 120 minutes, then it will create one function which will do a calculation & return values to enum constant:

Example

function Totalminute(hr: number): any {
  return 60 * hr;
}
enum hours {
  One = Totalminute(1),
  Two = Totalminute(2),
  Three = Totalminute(4),
}
console.log(hours.One);
console.log(hours.Two);
console.log(hours.Three);

Output

Value

String enum

It is the same as the numeric enums, we are just passing string values/literals to our enum constant. the 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

enum vehicleTurn {
  Left = "Left",
  Right = "Right",
  UTurn = "UTurn"
}
console.log(vehicleTurn.Left);
console.log(vehicleTurn.Right);
console.log(vehicleTurn.UTurn);

Output

output

Heterogeneous enums

Typescript allows us to create a mixed type of enums.

This means we can assign numeric & string-type values to enums.

Consider the below example, circleInfo has heterogeneous enum values.

Example

enum circleInfo {
  Area = "area of circle",
  Pie = 3.112,
  Radius = 20
}
let result = circleInfo.Pie * circleInfo.Radius * circleInfo.Radius;
console.log(circleInfo.Area + " is: " + result);

Output

Area of circle

Point A - Function & interface using enum

Consider the below example, clothSize is an enum that contains some constants. IClothSize is an interface that contains two properties, key & value, having string & number types respectively.

The function is taking an enum as a parameter & prints the data on the console.

Example

enum clothSize {
  small,
  medium,
  large
}
interface IClothSize {
  key: string,
  value: number
}
function getClothSize(size: clothSize): IClothSize {
  switch (size) {
    case clothSize.small:
      return {
        key: clothSize[clothSize.small], value: 10
      };
    case clothSize.medium:
      return {
        key: clothSize[clothSize.medium], value: 20
      };
    case clothSize.large:
      return {
        key: clothSize[clothSize.large], value: 30
      };
  }
}
console.log("cloth is " + getClothSize(clothSize.small).key + " & value is " + getClothSize(clothSize.small).value);
console.log("cloth is " + getClothSize(clothSize.medium).key + " & value is " + getClothSize(clothSize.medium).value);

Output

Cloth is small

Point B - const enum

  • Typescript allows us to declare a const enum.
  • const keyword is used.
  • It has inlined values.
  • We can access enum using enum['ConstantName']

Example

const enum myColor {
  Red = 10,
  White = Red * 4,
  Blue = White + 10,
  Yellow,
}
console.log(myColor.Red);
console.log(myColor.White);
console.log(myColor.Blue);
console.log(myColor['Yellow']);

Output

Ten

We will not be able to access an enum using index in a const enum like myColor[0], it will give us an error.

Point C

ES6 allows us to use map enum keys.

Example

enum classes {
  I,
  II,
  III,
  IV,
  V
}
const ClassNames = new Map<number, string>([
  [classes.I, '100'],
  [classes.II, '200'],
  [classes.III, '300'],
]);
console.log(ClassNames);

Output

Map

We will modify the above example, we can use this in classes as below.

Note

User can modify the code as per their requirement.

Example

enum classes {
  I,
  II,
  III,
  IV,
  V
}
const ClassNames = new Map<number, string>([
  [classes.I, '100'],
  [classes.II, '200'],
  [classes.III, '300'],
]);
class AllStandards {
  public allNames: object;
  constructor() {
    this.allNames = ClassNames;
  }
}
let obj: AllStandards = new AllStandards();
console.log(obj.allNames);

Output

Map

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.

export enum sportActivities {
  Football,
  Cricket,
  Badminton,
  Tennis
}

To import the enum in .ts, i.e.; the typescript file looks like this.

import {sportActivities} from '../enums'  

Summary

In this article, you learned about enum in Typescript.


Similar Articles