Enums in Typescript

Enums are special, they can make it easier to document intent, or create a set of distinct cases. When writing code we sometimes want custom, named constants that can make our code more readable while maintaining integrity, other languages such as Java and Kotlin have enums whereas Javascript doesn't. Typescript being a superset of javascript brought in some of these simple yet vital features that enhance the development experience.

Typescript integrated enums into the language pretty neatly, we can do a lot of amazing things with them. A classic example is when we want to have constant values for all available options for property types, for our example we'll have 3: residential, commercial and mixed use.

Now in javascript we'd have to create const variables and assign them specific values that would represent the different options. this is what it'd look like:

export const residential = 0; // or "residential"
export const commercial = 1; // or "commercial"
export const mixedUse = 2; // or "mixed_use"

// we'd then call each one whenever we need it

With typescript all we'd have to do is create one enum and use it's values anywhere in the project. Here's how we'd achieve the same in typescript:

export enum PropertyTypes {
    RESIDENTIAL, COMMERCIAL, MIXED_USE
}

// we'd then call it anywhere, like so:
PropertyTypes.RESIDENTIAL

This makes it easier to manage these values and effectively use conditional clauses like if/else or switch.

Since this isn't available in javascript, our enums won't be enums at runtime; typescript converts them to iifes(immediately invoked function expressions), something that js can process.

Constant vs computed enums

When we create an enum there's some javascript code that's generated at runtime, the iife, these are computed enums. If we don't want an this we can create a constant enum, though limited in scope constant enums don't have the generated code. To create one simple add the const keyword before the enum keyword, for example:

export const enum PropertyTypes {
    RESIDENTIAL, COMMERCIAL, MIXED_USE
}

Conclusion

Enums are a great feature and make development easier by allowing you to write readable code while maintaining integrity. Try them out for yourself.

Resources

This was a light article on the topic, for more information about enums, here are some resources

Typescript handbook - Enums