What are Enums in Typescript


Borislav Hadzhiev

Sat Feb 20 20212 min read


Photo by Ben Turnbull

Enums theory #

Enums in typescript are very similar to javascript objects, in fact enums get compiled to javascript objects, when you run your code through the typescript compiler.

In any scenario where we would use an enum, we could use a normal object. But enums are useful when we want to inform the person reading our code that we are representing a group of very closely related values.

Example #

enum ShirtSizes { Small = 'S', Medium = 'M', Large = 'L', } function printSize(size: ShirtSizes) { console.log(`Size is ${size}`); } // printSize('A'); // Error - 'A' is not assignable to parameter of type ShirtSizes // printSize('S'); // Error - 'S' is not assignable to parameter of type ShirtSizes printSize(ShirtSizes.Small); // `Size is S`

In the above snippet we have the ShirtSizes enum - there are all values we know in advance and are closely related. By using an enum we inform the reader of our code that our application is only concerned with 3 types of shirt sizes - S, M, and L.

Notice that when we create an enum we also create a new type in our code - ShirtSizes. The function printSize takes an argument of type ShirtSizes which is an enum, so we can only pass in one of the three possible values as an argument to it.

Enums without specifying values #

You could also define an enum without specifying concrete values for the keys, if you don't care about the values.

enum ShirtSizes { Small, Medium, Large, }

In the above snippet Small is initialized as 0, Medium as 1 and so on. You can also define a starting point for the index:

enum ShirtSizes { Small = 1, // <-- 1 Medium, // <-- 2 Large, // <-- 3 }

When to use #

We use enums when we have a small set of values that we know ahead of time, that are closely related to one another.

For example the status of an email:

enum EmailStatus { Read = 'READ', Unread = 'UNREAD', Draft = 'DRAFT', }

Now we have signaled to anyone reading our code that our application is only concerned with 3 possible statuses of an email.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee