How to Use Enums in TypeScript

An enum, or an enumerated type, is a data structure that allows you to define a set of named values.

Enums provide a way to represent a fixed set of values as constants. They can help make your code more expressive and self-documenting by giving meaningful names to specific values. Here you will learn how it’s possible to use enums in TypeScript.

4

Creating an Enum

Enums generally represent a fixed number of options for a given value. For example, an enum representing primary colors might have fixed values for Red, Yellow, and Blue.

Enums represent data as a set of key/value pairs known as enum members. The key must always be a string. However, the value—an auto-incrementing number by default—can be numeric, a string, or computed.

Closeup of dark typewriter keys

You can create an enum inthe TypeScript languageusing theenumkeyword. Follow it with the enum’s name and a pair of curly braces ({}) containing the enum members.A common JavaScript naming conventionstates that enum names should start with a capital letter.

This example features an enum calledDirection. The enum has a member representing each direction: Up, Down, Left, and Right.

A dark monitor displaying TypeScript code in the VSCode editor.

Since this code doesn’t specify a value for each of the keys, TypeScript will automatically assign values. The first member, Up, will have a value of 0. The remaining members will each have a value 1 greater than the previous member’s. you’re able to explicitly declare this if you find it difficult to remember:

Or you can explicitly declare different values, leaving undeclared values to continue incrementing as before:

Dell monitor showing Windows 10 desktop

In this example, the Inactive member has a value of 10. This behavior applies to enums that only have numeric values, not those with string or heterogeneous members.

The Different Types of Enum

Enums in TypeScript have an implicit type they base on the type of values their members hold. The most common type is the numeric enum, whose behavior the previous section covers, but there are two variations.

String Enums

A string enum is an enum in which all its members are strings. Unlike numeric enums, where values are automatically assigned, you have to initialize each member with a string:

Although string enums don’t have auto-incrementing properties, they may make more sense if you serialize them. Their values should still be descriptive, without member names, while a set of numeric values may not be self-describing.

windows recovery environment on laptop screen.

Heterogenous Enums

Heterogenous enums are enums that contain both numeric and string members. For example:

Heterogeneous enums are useful when you have enum members that require different value types based on each member’s specific context or meaning. However, theTypeScript documentationdiscourages the use of heterogenous enums since they introduce complexity that can make your code more error-prone.

Computed and Constant Enum Members

Each enum member has a value, which can either be constant or computed.

Constant Enum Members

An enum member is constant if it satisfies any of the conditions below.

According to the TypeScript documentation, A constant enum expression is a subset of TypeScript expressions that can be fully evaluated at compile time. For instance, a string or a numeric literal.

For example, the members of the enums in the code block below are all constant:

When you transpile constant enum members into plain JavaScript, the generated code uses their literal values. This can be beneficial for performance and make debugging easier.

For example, here’s the transpiled version of the Season enum:

Computed Enum Members

you could use computed enum members to assign values to enum members based on expressions or other dynamic calculations. For example:

TheSizeenum has three members:Small,Medium, andLarge. It explicitly assigns the value 1 to the Small member. TheMediumandLargemembers use a functioncalculateSizeto compute their values at runtime.

When working with computed enum members, it’s important to note that the values are not known until runtime. This may introduce more complexity and potentialruntime errorscompared to enum members with constant values.

For example:

The code block above is the transpiled version of theSizeenum. Notice how TypeScript does not include the return values from calculateSize() in the JavaScript code. Instead, it includes the original function call so that JavaScript determines the values at runtime.

Accessing Enum Values

You can access the values of enum members using the object dot notation.

Reverse Mapping Numeric Enums

Reverse mapping in numeric enums refers to the ability to fetch the corresponding enum member name from its value. This can be particularly useful when working with numeric values, which you might need to decode.

By default, enum values in TypeScript are forward-mapped, meaning you may only access the value associated with a name. However, you can manually perform reverse mapping to retrieve the enum member based on its value.

ThisgetDirectionNamefunction performs reverse mapping by accessing the enum member name using its value as an index. The function takes adirectionValueas an argument and retrieves the corresponding enum member name usingDirection[directionValue].

Reverse mapping can be handy in scenarios where you have a numeric value and need to determine the corresponding enum member name. It provides a convenient way to work with enums in both forward and reverse directions.

There Are Many Applications of Enums

You can use enums in various scenarios, such as handling switch statements, defining function parameters, mapping data, and representing choices or settings.

Whether you need to represent a finite set of options or manage complex state transitions, enums in TypeScript are a valuable tool to enhance the clarity and structure of your code.

Many Node.js projects use TypeScript for its strict typing and object-oriented features. Learn how to get started right away.

My foolproof plan is to use Windows 10 until 2030, with the latest security updates.

It’s not super flashy, but it can help to keep your computer up and running.

Some subscriptions are worth the recurring cost, but not these ones.

Quality apps that don’t cost anything.

You’ve been quoting these famous films wrong all along!

Technology Explained

PC & Mobile