Typescript: Enum vs Union type in performance
About drawbacks of enum in typescript
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.
// enum.ts
enum Direction {
Up = UP',
Down = 'DOWN',
};console.log(Direction.Up);
In Vanila Javascript, you are likely to use an object literal in order to group related values together.
// enum.js
const Direction {
Up: 'UP',
Down: 'DOWN',
};console.log(Direction.Up);
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).
- If you use enum, it eventually creates an extra code(reverse mapping) which including IIFE.
- 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!
export enum Direction {
Up = 'UP,
Down = DOWN',
}export var Direction;
(function (Direction) {
Direction["Up"] = "UP";
Direction["Down"] = "DOWN";
})(Direction || (Direction = {}));
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.
const enum Direction {
Up = 'UP,
Down = DOWN',
}const direction = Direction.Up;// It will be converted to:
const direction = 'UP'
2. as const
as const
makes an object as readonly
. And it is converted to the same object in transpiling.
const Direction {
Up: 'UP',
Down: 'DOWN',
} as const;
3. Combination of as const and union type
You can use as const
and union type
together as an alternative to enum.
const Direction = {
Up: 'UP',
Down: 'DOWN'
} as const;type DirectionType = typeof Direction[keyof typeof Direction];
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.