DEV Community

Cover image for How Typescript Enums Work
Johnny Simpson
Johnny Simpson

Posted on • Originally published at fjolt.com

How Typescript Enums Work

Enums, short for Enumerations, are preset constants which can be defined by a developer for use elsewhere in the code.

For Javascript developers, the concept of enums is usually new, but they are relatively straight forward to understand. Enums add context to what we're writing.

How to define Enums

Enums can be defined in Typescript using the Enum keyword. Here is an example:

enum Pet {
    Dog,
    Cat,
    Goldfish,
    Skeleton
}
Enter fullscreen mode Exit fullscreen mode

By default, each of these will be assigned a value. So Dog will be 0, Cat is 1, and so on. Suppose we have a function, then, that generates pets. Before, we may have written this:

// Generate a Cat
generatePet(1);
Enter fullscreen mode Exit fullscreen mode

Now, we can add context to what we're doing, and use our enum list, to do this:

// Generate a Cat
generatePet(Pet.Cat);
Enter fullscreen mode Exit fullscreen mode

The above code is equivalent to what we did before, only we're using our enums instead.

So wait.. why use enums?

You may be wondering "what's the point?", and it's a valid question. Enums essentially allow us to give more context to what we are doing. Instead of having the user memorize a list of possible pet numbers, we can simple ask them to use the enum list. This also gives the next person who reads our code, a better idea of what we were trying to do.

Numeric and String Enums

We can define enums as numbers or strings. Let's look at these in a little detail.

enum Pet {
    Dog = 2,
    Cat,
    Goldfish,
    Skeleton
}
Enter fullscreen mode Exit fullscreen mode

Above, we have given Dog a numeric value of 2. Every item after that, will be incremented by 1, so Cat becomes 3, Goldfish becomes 4, etc, but you can also just define them as you please:

enum Pet {
    Dog = 2,
    Cat = 9,
    Goldfish = 15,
    Skeleton = 44
}
Enter fullscreen mode Exit fullscreen mode

Typically we don't mix strings and numbers to avoid confusion, but we can also define enums as entirely strings too:

enum Counting {
    One = "one",
    Two = "two",
    Three = "three"
}
Enter fullscreen mode Exit fullscreen mode

Enum Values from Functions

Enums can also be functions which return values. If you only define one value in an enum, functions must go at the end. If you put functions at the start, then all enums will require values. As such, the following throws an error:

// This will throw an error, since the function is at the start
// So typescript assumes all will be functions
enum Counting {
    One = getOne(),
    Two,
    Three,
}
Enter fullscreen mode Exit fullscreen mode

But this will not:

enum Counting {
    One,
    Two,
    Three = getThree(),
}
Enter fullscreen mode Exit fullscreen mode

In the above One returns 0, Two returns 1, and Three returns the value of getThree(). Our getThree() function, to give an example, may look like this (to return the value 3):

const getThree = function() {
    return 3;
}
Enter fullscreen mode Exit fullscreen mode

Calculated Enums

Enums may be calculated, (i.e. a calculation), or refer to other Enums as well. For example:

enum FirstEnum {
    One,   // Returns "0"
    Two,   // Returns "1"
    Three  // Returns "2"
}

enum AnotherEnum {
    One: FirstEnum.One, // returns FirstEnum.One, i.e. "0"
    Two: 1 + 1,         // Calculates and returns "2"
    Three: 1 * 3,       // Calculates and returns "3"
    Star: One           // Refers to AnotherEnum.One, returns "0"
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Enums are a powerful way in typescript to add more semantics to your code. They give you a good way to let people reading your code know what you were trying to accomplish, and thus improve the maintainability of what you've wriitten. They also make your life easier, by allowing you to reference standard constants across your codebase.

We hope you've enjoyed this guide to Typescript Enums! To learn more about TypeScript click here

Discussion (4)

Collapse
adam_cyclones profile image
Adam Crockett • Edited on

Woah woah woah, but why, I see you tried to explain it but I don't feel like it's cleared up anything. it gives context to numbers as options but we don't typically do this, we usually use use strings, variable names, etc. Numbers are in my experience never passed like this in JavaScript.

I guess numbers maybe have a smaller memory footprint than a string... Maybe, it's a stretch 😊

Collapse
smpnjn profile image
Johnny Simpson Author

I mean the core thing about enums is that they give type safety to specific sets of values. I've also mentioned that you can assign strings or functions to their values - are you looking at it from a memory perspective? This article is more of how you can use enums in TypeScript since some conventions differ from other languages, not how they can be memory efficient - and to be honest that isn't really true in Javascript, right, since enums decompile to objects, meaning they don't have any memory benefits like they would have in maybe other languages. Maybe web assembly will help with that though.

Collapse
adam_cyclones profile image
Adam Crockett

Full disclosure I'm a long time Typescript developer and super fan. So not looking at this from any other languages, memory footprint is still important even in a GC language like JavaScript.
After many years I still feel enums don't make much sense to me. I always end up using string literals "foo" | "bar" keyof typeof obj or something like that.

Thread Thread
smpnjn profile image
Johnny Simpson Author

Yeah, both are valid, enums can become especially useful in large projects with many developers where you want to standardise the options developers have at their disposal for colours, etc.