Write TypeScript like a pro. Typescript Icon

Follow the ultimate TypeScript roadmap.

Optimize Enums in TypeScript with "const"

Using Enums in TypeScript is a great way to access particular parameters that are meant to be shared across multiple files, for example access levels of a particular user or a particular constant.

But Enums generate a lot of code, and by introducing the const keyword in TypeScript alongside our Enums, we can alleviate a lot of generated code. This doesn’t come without some key considerations, however, so read on to find out more.

Typically, we would declare an Enum as follows:

enum Sizes {
  Small,
  Medium,
  Large,
}

The Enum could then be accessed like so:

const coffee = {
  name: 'Espresso',
  size: Sizes.Small, // 0
};

Looks harmless, right? But what about when our TypeScript code is compiled? Here’s the generated code:

var Sizes;

(function (Sizes) {
  Sizes[(Sizes['Small'] = 0)] = 'Small';
  Sizes[(Sizes['Medium'] = 1)] = 'Medium';
  Sizes[(Sizes['Large'] = 2)] = 'Large';
})(Sizes || (Sizes = {}));

const coffee = {
  name: 'Espresso',
  size: Sizes.Small,
};

That’s a fair amount of code to simply share a string variable (across multiple files).

By default Enums also create what’s called a Reverse Mapping. It means we can take the Enum property value and pass it into the Enum itself to get a more literal value:

const coffee = {
  name: 'Espresso',
  size: Sizes[Sizes.Small], // 'Small'
};

Pretty cool right? But, most of the time you probably won’t need this reverse mapping functionality, and if that’s the case then you can certainly benefit from introducing const into your codebase right away.

Here’s what we can change our Enum across to, introducing the const modifier before the enum declaration:

const enum Sizes {
  Small,
  Medium,
  Large,
}

📣 Warning! This removes the ability to have the reverse mapping behaviour, so if you rely on that, don’t use this approach.

The compiled output? Far less code from TypeScript:

const coffee = {
  name: 'Espresso',
  size: 0 /* Small */,
};

Using const enum means that the code is completely virtual, and is never compiled to actual code. Smaller bundles, less code, simple change. It’s a great addition and consideration to the TypeScript language and I’d highly encourage you to start using it!

💯 If you are serious about your TypeScript skills, your next step is to take a look at my TypeScript courses where you’ll learn beginner to advanced TypeScript concepts and practices to reach the next level.

Learn TypeScript the right way.

The most complete guide to learning TypeScript ever built.
Trusted by 82,951 students.

Todd Motto

with Todd Motto

Google Developer Expert icon Google Developer Expert

Related blogs 🚀

Free eBooks:

Angular Directives In-Depth eBook Cover

JavaScript Array Methods eBook Cover

NestJS Build a RESTful CRUD API eBook Cover