Typescript Enum All you need to know

A Typescript enum allows us to define the collection of related values to be used by name. They make the code easier to read. You may use them when you want to limit the values that a variable can take to a small set of possible values. Javascript does not support enums, hence typescript creates runtime artifact to support them ( Except, const enum which do not have a runtime artifact). TypeScript provides both numeric and string-based enums.

Where to use Enum

There are many use cases, where the enum is very useful. For Example, directions can only take four values northeastsouth, and west. We can use codes like N, E, S, & W to represent them. Another example is days of the week, which you can represent as 1 to 7. Traffic lights are another example where variable takes finite values like green, yellow, & red

The enums make the core more readable and less error-prone. For Example, using codes like 1,2, etc to represent days of the week is less readable compared to the Weekdays.Sunday, Weekdays.Monday.

It also makes it easier to change the values in the future, without breaking the code. For Example, if you decide to use the number instead of N, E, S, & W for directions, you can do so easily.

You can also make use of the string literal types or numeric literal types along with the union types. These literal types do not have runtime artifacts and hence may be preferable over the Enum. Choose one based on your preference..

How to Create Enum

We define an enum by using the enum keyword, followed by the name of the enum (Weekdays). Then we define the members of the enum. Each member must have a name (monday, tuesday, etc) and value (1,2, etc). The members are separated by a comma. The trailing comma is allowed & ignored. If we omit the value of a member, then the TypeScript increments the value of the preceding member by one and assigns it to the current member: If the preceding member is a string and error is thrown.

In the above example, we have initialized the values. But If we omit the values, then the typescript initializes it with the values starting from 0.

You will get the nice intellisense help, when you use them.

intellisense help in Typescript Enum

we can use the quote in the names of enum members as shown below

Types of Enum

There are three types enum‘s in Typescript.

  1. Numeric enums
  2. String enums
  3. Heterogeneous enums (both string & numbers)

Typescript enum does not support any other types other than numbers and strings as its member.

Numeric Enums

The Numeric enum stores the values as a number. You can define an enum without assigning a value as shown below. The Typescript automatically assigns the numeric values starting from 0. You can see from the following example that the Car,plane & train gets the value 0,1 & 2 respectively.

You can provide a starting number as shown in the example below. The plane & train automatically gets ( 3 & 4). i.e. the next available number.

The following example shows how to use enum as a return type

Computed enum

We can also include the members with computed values. They are allowed only in the case of numeric enums. The string & heterogeneous enums do not support computed enums.

You can use any function. The following code generates a random number from 10 to 20. Hence you will get a different number for the train on each run.

String Enums

We can also use the strings instead of numbers as values.The only difference is that the we must initialize the values.

Use it in a function as shown below

Heterogeneous Enums

The Heterogeneous enums allows mix of both string & number.

If you do not provide an initial value, the typescript will automatically assign a number incremented by one from the previous value. If the previous value is a string, then it will result in an error.

For Example, Train gets the value 2 here

This results in an error Enum member must have initializer.

Reverse Mapping of Enum

The Typescript generates a reverse mapping for numeric enum members. For Example

The Compiler emits the following code. As you can see from the code, the compile generates both the forward mapping (VehcileType["Car"] = 0) and reverse mapping (VehcileType[0] = "Car";) is a single statement VehcileType[VehcileType["Car"] = 0] = "Car";

Which means you can get the value of an enum from its name VehcileType["Car"] or get the name of enum from its value (VehcileType[0] )

The reverse mapping for numeric enum members works even in Heterogeneous Enums with number values as shown below. The string enum members do not support reverse mappings

Transpiled code.

Const Enums

If an enum is prefixed with the keyword const, it doesn’t get transpiled. i.e. no javascript code is emitted. Instead, the compiler will replace the value of its member directly in the transpiled code, wherever they are used.

Since they do no have runtime representation, you cannot use computed memeber

Type Checking

The Typescript performs a loose type checking when number members are involved. For example the someFn accepts VehcileType as argument. But someFn also accepts any number. Invoking someFn(100) with 100 as argument does not throw any errors.

But in case of string enums it works as expected.

The loose checking of type exists when you mix numbers & strings as in Heterogeneous enums.


Typescript Enums

2 thoughts on “Typescript Enum All you need to know”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top