TypeScript Tidbit: Const enums

Enums are a useful feature of TypeScript that allow you to define a set of named constants. A use case for enums, that I’m going to borrow straight from TypeScript’s documentation, is defining a direction:

enum Direction {
Up = 1,
Down,
Left,
Right,
}

After running the above through the TypeScript compiler you’ll end up with the following JavaScript:

var Direction;
(function (Direction) {
Direction[Direction["Up"] = 1] = "Up";
Direction[Direction["Down"] = 2] = "Down";
Direction[Direction["Left"] = 3] = "Left";
Direction[Direction["Right"] = 4] = "Right";
})(Direction || (Direction = {}));

There’s a bit to digest but the purpose of this post isn’t explaining how compiled enums work, but in short, it enables you to lookup the Key or Value of the enum.

Direction[“Up”] // 1
Direction[1] // Up

Having that lookup means a lot of code is generated that sometimes isn’t needed. I haven’t run into an instance where I have needed lookup functionality, so I didn’t know how much code was being generated for something I wasn’t using.

Const enums

const enum Direction {
Up = 1,
Down,
Left,
Right,
}

What’s new? The addition of the const keyword. What does the TypeScript compiler generate when the const keyword is added?

// ?

That isn’t a mistake, there is no code generated. Instead, TypeScript inlines the values when used within code. For example the following TypeScript:

if (someDirection === Direction.Up) {...}

Becomes:

if (someDirection === ‘up’) {...}

Great. It has saved potentially unnecessary code generation at the cost of the lookup ability. It’s worth considering const enums in your project to start with and then if you require the lookup later down the track, you could remove the const.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store