TypeScript Enums - Deep Dive

This article explains what are enums in Typescript and how we can use it in a real world scenario. Typescript Enums - Deep Dive

What are Enums?

Enums are specific way to create constants in typescript. In Object oriented programming languages such as Java or C#, it contains enums as a data types to create named constant based on the domain. Unfortunately, we don't have such data type in javascript. Typescript solves that problem for us. it brings the enums as a data type to javascript applications.

https://stackblitz.com/edit/typescript-vrbxlx?embed=1&file=index.ts

Why we need it?

One of the major questions that comes to our mind when we hear about enums are can't we just define constants and use it, because it seems similar? . Let's understand the benefit of enums over constants with an example.

Let's create a User Role Types such as USER , MODERATOR and ADMIN

1export const USER = "USER"
2export const MODERATOR = "MODERATOR"
3export const ADMIN = "ADMIN"

Now, we need to get the role and add it to the DB.

1const USER = "USER"
2const MODERATOR = "MODERATOR"
3const ADMIN = "ADMIN"
4
5function getData(user: string) {
6 console.log("USER", user)
7}
8
9getData("MODEARTOR")

problem with the above function is, we don't know what value is passed into the function. we all know that it is of type String.but will it throw an error if the value is not in the specified list?.

We can solve this problem using Enum

1enum ROLE {
2 USER = "USER",
3 MODERATOR = "MODERATOR",
4 ADMIN = "ADMIN",
5}
6
7function getData(user: ROLE) {
8 console.log("USER", user)
9}
10
11getData(ROLE.MODERATOR)

Enums helps us to organise the related values together. think of it like a group of values that brings a domain entity together.

Another problem with constants are reusability. Let's say you use the constant in another file and someone changes the source constant variables. you might end up refactoring in all the places where the constants is used.

we can solve the problems using enums,

1enum ROLE {
2 USER: "USER",
3 MODERATOR: "MODERATOR",
4 ADMIN : "ADMIN"
5}

By declaring it as enum, you can easily check the type of variable where we use enums. For example,

1let userRole = ROLE.USER

Now, you don't need to worry about the change because. even if someone changes the value of enum, still it is going to work perfectly on all the implemented code.

Types of Enums

There are four types of enums in typescript. they are,

Number Enums

it contains numbers as the value. For example, Status entity in our application business logic. it can be a numeric values.

1enum STATUS {
2 ACTIVE = 0,
3 INACTIVE = 1,
4 PENDING = 2,
5}
6
7console.log(STATUS.INACTIVE)

Numeric enums are incremental by default. we can just define the first value in the enum and it will increment by default.

1enum STATUS {
2 ACTIVE = 0,
3 INACTIVE,
4 PENDING,
5}
6
7console.log(STATUS.INACTIVE) //Results in 1

At the same time, we can start the initial value other than zero as well,

1enum STATUS {
2 ACTIVE = 11,
3 INACTIVE,
4 PENDING,
5}
6
7console.log(STATUS.INACTIVE) //Results in 12

String Enums

String enums will contains string as value. A good example would be User Role that we have seen in the beginning.

1enum ROLE {
2 USER = "USER",
3 MODERATOR = "MODERATOR",
4 ADMIN = "ADMIN",
5}
6
7console.log(ROLE.MODERATOR)

Heterogenous Enums

it allows us to have both String and numeric values in the enums

1enum STATUS {
2 ACTIVE = "ACTIVE",
3 INACTIVE = 2,
4 PENDING = 3,
5}

Although, we have this options. it is better not to use in that way. it might be hard to manage the code using this type of enum.

Computed Enums

the value of enums can also be computed value. it can be a function invocation which returns a specific type of value.

1enum Weekend {
2 Friday = 1,
3 Saturday = getDate("TGIF"),
4 Sunday = Saturday * 40,
5}
6
7function getDate(day: string): number {
8 if (day === "TGIF") {
9 return 3
10 }
11}
12Weekend.Saturday // returns 3
13Weekend.Sunday // returns 120

One important thing to note here is, when a enum includes a computed value. then, uninitiated enum must come first or it should come after the numeric values. else, typescript will start screaming

TypeScript%20Enums%20Deep%20Dive%2061adb0236aaf4643937513d5c3edd4c3/Screenshot_2020-06-08_at_1.50.09_PM.png

Real Wold Use-cases

One of the main use-case of enums is to group related constant. For example,

  • Status of of Application Status. NEW , IN PROCESS and COMPLETED
  • File Access that we discussed in this article.
  • User Role Access

Enums can be used wherever we need to group some constants to achieve the business logic. Also, it is better to use enums if there is a need for switch statement in javascript.

References:

https://www.typescriptlang.org/docs/handbook/enums.html

To Read More

How to build an Actionable data ta...

In this article, we will see how to build an Actionable data table using a react...

How to Integrate Google Sheet in No...

This article explains how to Integrated Google sheet with your Nodejs Applicatio...

Kubernetes for Nodejs developers

Do you keep hearing the word kubernetes in the tech community and you couldn't u...