Don't use Enums in Typescript, they are very dangerous 😨
Tags: typescript, javascript
Published: 2023-01-20 20:44:13

Have you ever wondered why TypeScript experts recommend avoiding the use of ENUMs? While they may seem like a useful tool for defining a set of constant values, they are actually very dangerous. In this article, we will show you why and how to avoid their use. You'll discover that there are much safer and reliable alternatives that you can use instead. Get ready to be surprised! 😱

## Enum's emit code

One of the reasons why it is recommended not to use it is due to the generation of code at the time of compiling the app. ENUMs generate additional code at compile time, which increases the size of the final file. This can have a negative impact on the loading speed and performance of the app.

**Define our Roles enum**

```ts
enum Roles {
  Admin,
  Writer,
  Reader
}
```

**Output (Build-generated code)**

```ts
var Roles;
(function (Roles) {
    Roles[Roles["Admin"] = 0] = "Admin";
    Roles[Roles["Writer"] = 1] = "Writer";
    Roles[Roles["Reader"] = 2] = "Reader";
})(Roles|| (Roles = {}));
```

While it's true that this detail is fixed if you use a constant enum, but I've been on multiple projects and seen people using regular enums everywhere and wonder why their output is so big. 

> Postada: I have been one of those people. 😁

This may seem trivial, but imagine that you have files shared between the "Frontend" and "Backend" you can end up with quite heavy bundles.

Okay, that's one thing, and we can handle that by enforcing the constants. But there is also this unpleasant ambiguity.

## Numeric types usafe

Yes, you read it right. This is not clickbait. Regular numeric enums, such as in an enum where you don't set string values, are not type safe! If we look back at the Roles enumeration from earlier, a function that takes user roles also takes any numeric value instead.

```ts
enum Roles {
  Admin,
  Writer,
  Reader
}

declare function hasAccess(role: Roles): void;

hasAccess(10);
// ☝️ Worst of all, this is ok! 😱
```

As you may have noticed, when the `hasAccess(10)` function is called, a numeric value is being passed that is not part of the enum Roles, this is allowed in TypeScript, and this is what is considered a problem, since it allows the entry of unexpected and unverified values which can cause security and performance problems in the app.

## String ENUM's are named types

In a world where structural types are common, ENUMs choose to be a named type. This means that even if the values are valid and supported, they cannot be passed to a function or object where a string enumeration is expected. Let's see this example:

```ts
enum Roles {
  Admin = 'admin',
  Writer = 'writer',
  Reader = 'reader'
}

declare function hasAccess(role: Roles): void;

hasAccess('admin') // Invalid.
hasAccess(Roles.Admin) // Valid.
```

As you can see enums are a named type and only accept enum-specific values, not compatible or similar values, which can lead to compatibility issues and should be carefully considered when designing and using enums.

## Solution

A much safer alternative and guarantee of compatibility is the use of objects. Let's see the following example:

```ts
const Roles = {
  Admin: "admin",
  Writer: "writer",
  Reader: "reader"
} as const;

// Convert object key in a type
type RoleKeys = typeof Roles[keyof typeof Roles]

declare function hasAccess(role: RoleKeys): void;

// 💥 Error!
move('guest');

// 👍 Great!
move('admin');

// 👍 Also great!
move(Roles.Admin);
```

## Conclusion

ENUMs may seem like a useful tool for defining a set of constant values, but they are actually very dangerous. Excessive use of regular ENUMs can lead to code size issues, security issues, scalability issues, and maintainability issues.

Instead of using ENUMs, it's better to opt for objects or types. Objects are flexible and scalable, which means that they can be modified at runtime and new values can be added. Types are also flexible and scalable, and also offer better code clarity and readability. Also, objects and types are less prone to bugs and security issues compared to ENUMs. In short, using objects or types instead of ENUMs is a better option in terms of flexibility, scalability, clarity, readability, and security.

## Follow me ❤️

- [Twitter](https://twitter.com/thebug404). 🐦
- [Github](https://github.com/thebug404). 🐙