const enum vs enum
Written byPhuoc Nguyen
Created
27 Aug, 2020
Category
TypeScript
An enum can be declared with or without the
`const`
keyword. Here are the examples of a regular enum:js
enum Direction {
Up,
Down,
Left,
Right
}
and a
`const`
enum:js
const enum Light {
Red,
Green,
Blue
}
#Differences
-
TypeScript compiles regular enum to JavaScript objects. Given the
`Direction`
enum above, it will be transpiled to the following JavaScript code:jsvar Direction;(function (Direction) {Direction[(Direction['Up'] = 0)] = 'Up';Direction[(Direction['Down'] = 1)] = 'Down';Direction[(Direction['Left'] = 2)] = 'Left';Direction[(Direction['Right'] = 3)] = 'Right';})(Direction || (Direction = {}));On the other hand, the`Light`
enum is not transpiled at all. You will see nothing if the enum is not used.In the other cases, all the enum references are replaced by the inline codes. For example,`console.log(Light.Red)`
is compiled as`console.log(0 /* Red */)`
. -
Because there is no JavaScript object that associates with
`const`
enum is generated at run time, it is not possible to loop over the`const`
enum values.TypeScript will throw an error when we try to iterate over the`Light`
enum:js// ERRORfor (let i in Light) {console.log(i);}
#Good to know
If you do not want TypeScript to erase the generated code for
`const`
enums, you can use the `preserveConstEnums`
compiler flag.#See also
Questions? 🙋
Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Recent posts ⚡
Newsletter 🔔
If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn