Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

How to Use Enum in Typescript

Learn about Typescript, including Create Enum, key uses, practical steps, common issues, and answers to frequently asked questions.

Table of Contents

Typescript guide image 1

This practical guide explains how to use enum in typescript with clear steps and useful context. It also covers common requirements, potential problems, and the details that can help you get better results.

Create Enum

Enum usually represents some fixed selection of a supplied value. For example, an enum representing the primary colors might contain fixed values for Red, Yellow, and Blue.

Enum represents data as a key/value pair called an enum (component) member. This key should always be a string. However, the value - which defaults to an auto-incrementing number - can be numeric, string, or calculated.

You can create enums in TypeScript language using enum keyword. It is followed by the name of the enum and a pair of curly braces ({}) containing the enum's members. A common JavaScript naming convention states that enum names must start with a capital letter.

enum Direction { Up, Down, Left, Right }

This example includes an enum named Direction . This enum has a member representing each direction: Up, Down, Left and Right.

Since this code does not define a value for each key, TypeScript will automatically assign the value. The first component - Up has the value 0. The remaining components will in turn have a value greater than 1 compared to the number of previous components. You can explicitly declare this if you find it difficult to remember:

enum Direction { Up = 0, Down = 1, Left = 2, Right = 3, }

Or you can declare other values, leaving the undeclared values to continue incrementing as before:

enum Status { Active = 9, Inactive, // 10 }

In this example, the Inactive element has a value of 10. This operation applies to enums that have only numeric values, not string or heterogeneous elements.

Different Enum Types

Enums in TypeScript have an implicit type that they are based on the type of value their elements hold. The most common type is the numeric enum, which has two variants.

Enum String

A string enum is an enum whose members are all strings. Unlike numeric enums, where values are automatically allocated, you must initialize each element with a string:

enum PrimaryColors { Red = "RED", Yellow = "YELLOW", Blue = "BLUE" }

While string enums don't have auto-increment properties, they might make more sense if you serialize them. Their values should still be descriptive, with no member names, while a set of numeric values may not be self-descriptive.

Enum Is Not Uniform

A heterogeneous enum is an enum that contains both numeric and string elements. For example:

enum PrimaryColors { Red = "RED", Yellow = "YELLOW", Blue = "BLUE" }

Heterogeneous enums are useful when you have enum elements that require a different value type based on the context or specific meaning of each element. However, the TypeScript documentation discourages the use of heterogeneous enums because they introduce complexity that can make your code more error prone.

Enum Elements Are Calculated and Constant

Each emum element has a value, which can be constant or computed.

Constant Enum Component

The enum element remains unchanged if it satisfies any of the below conditions.

  1. The first element of the enum and no initializers.
  2. Without an initializer, the previous enum was a constant.
  3. Initialized with a constant enum expression.

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

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

enum Direction { Up, Down, Left, Right } // CASE 2 enum Weekday { Monday = 1, Tuesday, Wednesday, Thursday, Friday } // CASE 3 enum Season { Spring = "SPRING", Summer = "SUMMER", Autumn = "AUTUMN", Winter = "WINTER" }

When converting constant enum members to plain JavaScript, the generated code will use their literal values. This can benefit performance and make debugging easier.

For example, here's the translated version of the Season enum:

var Season; (function (Season) { Season["Spring"] = "SPRING"; Season["Summer"] = "SUMMER"; Season["Autumn"] = "AUTUMN"; Season["Winter"] = "WINTER"; })(Season || (Season = {}));

Calculated Enum Component

You can use computed enum elements to allocate values to enum elements based on expressions or other dynamic computations. For example:

enum Size { Small = 1, Medium = calculateSize(12), Large = calculateSize(5) } function calculateSize(value: number): number { return value * 5; } console.log(Size.Large)

Enum Size has 3 components: Small, Medium and Large. It explicitly assigns the value 1 to the Small member explicitly. The Medium and Large members use the Size function to calculate their values at runtime.

When working with computed enums, it is important that you record values that are unknown until runtime. This can add complexity and potential runtime errors compared to enum elements containing constant values.

For example:

var Size; (function (Size) { Size[Size["Small"] = 1] = "Small"; Size[Size["Medium"] = calculateSize(12)] = "Medium"; Size[Size["Large"] = calculateSize(5)] = "Large"; })(Size || (Size = {})); console.log(Size.Large)

The above code block is a transcoded version of enum Size . Notice how TypeScript does not include the return values from calculateSize() in the JavaScript() code. Instead, it involves calling the initial function so that JavaScript determines the value at runtime.

Accessing Enum Values

You can access the values of the numeric component using object dot notation.

For example:

enum Direction { Up = 0, Down = 1, Left = 2, Right = 3, } console.log(Direction.Left) // 2

Invert Enum Number Mapping

Invert the mapping in a numeric enum that references the fetching the corresponding enum element name from its value. This can be especially useful when working with numeric values that you need to decode.

By default, enum values in TypeScript are mapped to, meaning you can only access the value associated with the name. However, you can reverse the mapping yourself to retrieve the enum based on its value.

For example:

enum Direction { Up = 1, Down, Left, Right } function getDirectionName(directionValue: number): string { // Reverse mapping const directionName = Direction[directionValue]; return directionName; } console.log(getDirectionName(1)); // "Up" console.log(getDirectionName(3)); // "Left"

The getDirectionName function implements inverse mapping by accessing the enum element name with its value as an index. This function takes directionValue as an argument and retrieves the corresponding enum element name with Direction[directionValue] .

Reverse mapping can be useful in contexts where you have numeric values and need to decide on the corresponding enum element name. It provides a convenient way to process enums in both forward and reverse directions.

Here's what you need to know about using enums in TypeScript . Hope the article is useful to you.

Conclusion

Understanding Typescript makes it easier to compare options, avoid common mistakes, and apply the information in this guide more effectively. Review the relevant requirements before making changes or choosing a solution.

FAQ

How do you use enum in typescript?

Follow the steps in this guide in order, confirm the required settings or tools, and verify the result before making additional changes.

Is it safe to use enum in typescript?

It is generally safe when you follow the recommended instructions, use trusted tools, and avoid changing settings you do not understand.

What should you do if the process does not work?

Recheck the requirements, restart the device or application when appropriate, and review each step for missed settings or compatibility issues.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.