Typescript: Enum vs Union type in performance

About drawbacks of enum in typescript

Suyeon Kang
suyeonme
2 min readMar 24, 2022

--

Photo by Steve Johnson on Unsplash

Many programming languages provide enum as a built in functionality. However, Javascript doesn’t support it. Typescript provides enum which doesn’t exists in javascript by converting enum to IIFE(Immediately-Invoked Function Expression) in transpiling.

So, how enum is transpiled in javascript? Let’s look closer enum first.

Enum in typescript

What is enum?

Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums. — Typescrpt Handbook

You can group and save the related values using enum. The values of enum can be string, numeric or mix together.

In Vanila Javascript, you are likely to use an object literal in order to group related values together.

Disadvantages of using enum

The Javascript transpiler creates an object at runtime when evaluating enum because of reverse mapping (String enum doesn’t have reverse mapping).

  1. If you use enum, it eventually creates an extra code(reverse mapping) which including IIFE.
  2. IIFE is not a target for a tree-shaking in specific bundlers, like rollup.js. It might increase a bundle size, potentially.

➡️ rollup.js fixed the issue now!

Alternative

Below options would be an alternative unless you need a reverse mapping.

1. const enum

const enum doesn’t create any extra code(reverse mapping) as well as being a target for tree-shaking.

2. as const

as const makes an object as readonly. And it is converted to the same object in transpiling.

3. Combination of as const and union type

You can use as const and union type together as an alternative to enum.

Conclusion

Using enum is pretty handy but it might require an extra cost in some case. So it is up to you deciding when to use enum.

Happy Coding.

--

--