Difference between enum and const enum in Typescript

Enums are a powerful construct to reduce errors in your code. Instead of typing a string, and possibly mistyping the value, using an 'enum' lets the compiler throw you an error at compile time. It also helps in refactoring your code (the editor can figure out all places you used the enum value).

However, there are a few things to remember about how enums show up in the final JavaScript output.

Here is an example:

enum Direction {
    UP,
    DOWN,
    LEFT,
    RIGHT
}

const north: Direction = Direction.UP;

Considering the fact that JavaScript doesn't have a concept of enums, the actual output will be this:

var 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 = {}));
const north = Direction.UP;

Notice the amount of code that was spit out.

What happens if we turn our enum into a const enum? The answer is actually quite simple - nothing gets spit out to our JavaScript. In other words, it's as if the enum never existed!

The reason for this is quite simple. If you know how const works in C#, you probably know the answer already. Basically, the compiler goes to the place where you used the enum, and literally, replaces it with the actual value.

Here is what I mean:

enum Direction {
    UP,
    DOWN,
    LEFT,
    RIGHT
}

let north: Direction = Direction.UP;

The output will be:

let north = 0 /* UP */;

Notice that now our output has the value 0 for north - a literal value for UP.

There is a caveat though. Using const enum means that you lose some of the functionality you can get from enums. For example, you cannot do this:

const enum Direction {
    UP,
    DOWN,
    LEFT,
    RIGHT
}

const north: Direction = Direction.UP;
console.log(Direction[north]); // ERROR.

Without const, you would get the value 'UP', but because this is a const enum, we don't have the ability to get the actual value of the north direction.

Another thing you may consider is creating a type.

Here is an example:

type Direction = 'UP' | 'DOWN' | 'LEFT' | 'RIGHT';
const north: Direction = 'UP';

The compiled output will be:

const north = 'UP';

Notice how you are not able to set a base value to UP. For example, you can't set UP to '0'.

Happy coding!