TypeScript Enums - Deep Dive
Tags: webdev, showdev, typescript, javascript
Published: 2020-06-16 14:59:49

---
title: TypeScript Enums - Deep Dive
published: true
description: This article explains what are enums in Typescript and how we can use it in a real world scenario. Typescript Enums - Deep Dive
tags: webdev,showdev,typescript,javascript
canonical_url: https://cloudnweb.dev/2020/06/typescript-enum-deep-dive
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/4n6fkxsir943tz2vvbqr.png
---
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](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`

```tsx
export const USER = "USER"
export const MODERATOR = "MODERATOR"
export const ADMIN = "ADMIN"
```

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

```tsx
const USER = "USER"
const MODERATOR = "MODERATOR"
const ADMIN = "ADMIN"

function getData(user: string) {
  console.log("USER", user)
}

getData("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`

```tsx
enum ROLE {
  USER = "USER",
  MODERATOR = "MODERATOR",
  ADMIN = "ADMIN",
}

function getData(user: ROLE) {
  console.log("USER", user)
}

getData(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,

```tsx
enum ROLE {
  USER: "USER",
  MODERATOR: "MODERATOR",
	ADMIN : "ADMIN"
}
```

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

```tsx
let 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.

```tsx
enum STATUS {
  ACTIVE = 0,
  INACTIVE = 1,
  PENDING = 2,
}

console.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.

```tsx
enum STATUS {
  ACTIVE = 0,
  INACTIVE,
  PENDING,
}

console.log(STATUS.INACTIVE) //Results in 1
```

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

```tsx
enum STATUS {
  ACTIVE = 11,
  INACTIVE,
  PENDING,
}

console.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.

```tsx
enum ROLE {
  USER = "USER",
  MODERATOR = "MODERATOR",
  ADMIN = "ADMIN",
}

console.log(ROLE.MODERATOR)
```

### Heterogenous Enums

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

```tsx
enum STATUS {
  ACTIVE = "ACTIVE",
  INACTIVE = 2,
  PENDING = 3,
}
```

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.

```tsx
enum Weekend {
  Friday = 1,
  Saturday = getDate("TGIF"),
  Sunday = Saturday * 40,
}

function getDate(day: string): number {
  if (day === "TGIF") {
    return 3
  }
}
Weekend.Saturday // returns 3
Weekend.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

<p style="text-align:center">
<img src="https://media.giphy.com/media/3o6gb27m9SE4PPJyFy/giphy.gif"/>
</p>

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/3kkka4d22yueqbm5sz7g.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](https://www.typescriptlang.org/docs/handbook/enums.html)