How to use Enum in TypeScript

An Enum is a data structure that allows you to define a set of named values. Here's how to use enums in TypeScript.

Picture 1 of How to use Enum in TypeScript

Enum provides a way to represent a fixed set of values ​​as a constant. They can help you write more impressive code and document your own by giving meaningful names to specific values.

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.

Update 04 August 2023
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile