<img alt="TypeScript Enums Explained The Key to Code Clarity" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/TypeScript-Enums-Explained-The-Key-to-Code-Clarity.jpg/w=800" data- decoding="async" height="420" src="data:image/svg xml,” width=”800″>

TypeScript enums is a phrase that will encounter a lot when dealing with TypeScript language.

TypeScript is among the youngest but is also ranked as one of developers’ most popular programming languages. TypeScript is an extension (superset) of JavaScript. Thus, any valid JavaScript code is also valid in TypeScript. However, TypeScript introduces static typing capabilities (a missing feature in JavaScript). 

What are TypeScript Enums, their use cases, and how can you create them? This article will cover everything you need to know about Enums. 

What are TypeScript Enums?

<img alt="typescript" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/typescript.png/w=800" data- decoding="async" height="400" src="data:image/svg xml,” width=”800″>

Enums (enumerated types) are data structures of constant length that hold a set of unchanging values (constants). TypeScript is not the only language that uses Enums, as they are available in object-oriented languages like C# and Java. 

In TypeScript, enums allow developers to create a set of distinct cases or document intent. They are also important in setting values or properties that can only be a certain number of values. For instance, there can only be seven continents in the world. 

In summary, TypeScript enums are important in the following ways;

  • They are flexible as they allow developers to document and express intentions and use cases easily
  • Enums allow developers to create energy-efficient custom constants in JavaScript
  • Saves compile and runtime when compiling TypeScript code into JavaScript code

TypeScript Enums can either be strings or in numeric form. However, these enums are preprocessed and do not undergo testing during the testing phase. TypeScript translates/ converts enums into JavaScript code. 

Different Enums in TypeScript

Now that you understand Enums, it is time to see them work in TypeScript. You can set up a development server by downloading TypeScript and Node.js on your local machine or using online solutions. We will use the TypeScript Playground to demonstrate different TypeScript enums. 

These are the different Enum Types in TypeScript;

#1. Numeric enums 

You need to use the keyword ‘enum’ and follow it with the name of the enum you want to create. After that, you create curry brackets that will specify the members of the enum. This is an example of a numeric enum;

enum CardinalDirections {
  North = 5,
  East,
  South,
  West,
};

The above represents an enum named CardinalDirections that has four members. In this case, there can only be four values (North, East, South, and West), making enum an excellent choice to hold data. 

I have assigned CardinalDirections.North value 5. However, I have not assigned the others values because TypeScript will do the rest automatically. For instance, the value for CardinalDirections.East will be 6 as TypeScript increments the previous value by 1.

The CardinalDirections.West will be 8. 

What if we don’t assign a value to the first item inside the curry brackets? Our enum will be;

enum CardinalDirections {
  North,
  East,
  South,
  West,
};

TypeScript will automatically assign North value 0. If you key in something like CardinalDirections.West, you will get 3

#2. String enums

Each member in a string enum has to be initialized with another string enum member or a string literal. This is an example of a string enum;

enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT",
}

This enum does not increment like what happens in numerical enums. If you run this code; 

enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT",
}
console.log(Direction.Right)

This is what you get;

“RIGHT”

#3. Heterogeneous enums

You can mix numeric and string members to form a Heterogeneous enum. This is an example; 

enum HeterogeneousEnum {
  No = 0,
  Yes = "YES",
}

#4. Constant and computed enum members

Enum members have values associated with them, which can be ‘constant’ or ‘computed’. 

This is an example of a constant enum;

enum E1 {
  X,
  Y,
  Z,
}

In this case, the first member of the enum does not have an initializer, and TypeScript assigns it value 0.

You can also consider this example;

enum E1 {
  X=1,
  Y,
  Z,
}

This is also a constant enum, as the first member is assigned a value, and the incremental rule is applied to the rest. 

Computed enums mix constant and computed members. Check out this example;

enum Color {
  Red = 100,
  Green = (Math.random() * 100),
  Blue = 200
}

Enum member ‘Blue’ is a constant member. On the other hand, enum member ‘Green’ is an enum computed with the Math.random() function at runtime. 

#5. Const enums

const enums are used to boost the performance of numeric enums. In this case, we declare the enum as a const. 

Consider this code that shows the days of the week;

enum Weekday {
  Monday = 1,
  Tuesday,
  Wednesday,
  Thursday,
  Friday
}

If we run console.log(Weekday.Thursday), we get our answer as 4. However, if we check the JavaScript generated at compile time, we get this;

"use strict";
var Weekday;
(function (Weekday) {
    Weekday[Weekday["Monday"] = 1] = "Monday";
    Weekday[Weekday["Tuesday"] = 2] = "Tuesday";
    Weekday[Weekday["Wednesday"] = 3] = "Wednesday";
    Weekday[Weekday["Thursday"] = 4] = "Thursday";
    Weekday[Weekday["Friday"] = 5] = "Friday";
})(Weekday || (Weekday = {}));
console.log(Weekday.Thursday);

We can change this code and declare ‘Weekday’ as a constant;

const enum Weekday {
  Monday = 1,
  Tuesday,
  Wednesday,
  Thursday,
  Friday
}

If we run this code console.log(Weekday.Thursday), the JavaScript that will be generated at compile time will be;

"use strict";
console.log(4 /* Weekday.Thursday */);

You can see that the JavaScript code at compile time is optimized when you declare your enum as a const. 

#6. Ambient enums

Ambient enums use the ‘declare’ keyword to describe the shape of already existing enum types. Consider this example;

declare enum Color {
  Red,
  Green,
  Blue
}

Ambient enums are declared outside any module and can be used to create reusable types. As such, you can always import ambient enums and use them in your components as long as they are declared globally. 

You now understand the different enum types in TypeScript. We can now show how you can use enums in different ways. This will be our reference code;

enum Direction {
  North = 'N',
  East = 'E',
  South = 'S',
  West = 'W',
};

These are some use cases;

  • Extract enum members. For instance, if we want to access North, we can use

console.log(Direction.North); // Outputs: 'N'

  • Use enum members: You can pick a certain enum member to represent a specific direction. For instance, 
const currentDirection = Direction.East;
console.log(`The current direction is ${currentDirection}`);

This will give this output “The current direction is E”

Enums vs. Object Maps in TypeScript

Enums are used to represent a finite set of values. For instance, the colors of the rainbow or days of the week. Enums are strongly typed, meaning they capture any errors during development. This is an example of a TypeScript enum;

enum Color {
  Red,
  Green,
  Blue,
}

Object Maps/ dictionaries/ key-value pairs store and retrieve values associated with specific keys. You can use TypeScript Object Maps to store any type of data. However, they are not strictly typed, meaning type errors might not be captured during development. This is an example of an Object Map of the same colors;

const colors = {
  red: "FF0000",
  green: "00FF00",
  blue: "0000FF",
};

The major differences between enums and object maps in TypeScript are;

  • Enums are strictly typed, while object maps are not
  • Enums are a ‘Type’, while object maps are a data structure
  • Enums are not flexible, while object maps are flexible

Best Practices of Using Enums in TypeScript

We have already stated that TypeScript is not the only programming language with the enums feature. Following the best practices ensures you write clean, optimized, and bug-free code. These are some of the best practices when writing/ using TypeScript enums;

  • Capitalize enum names: Always capitalize the first word when naming an enum. For instance, it is always advisable to have an enum ‘Number’ instead of ‘number’.
  • Use enums for constants: Enums are best used to declare a fixed set of related items. For instance, there can only be 7 days in a week. The enum members should never change during execution. 
  • Avoid overusing enums: You may have just learned a new concept and want to use it almost everywhere in your TypeScript project. However, always use TypeScript enums in moderation. TypeScript enums are a good choice when you want to maintain code readability. 
  • Consider enums as enums: You can use TypeScript enums for different purposes. However, the best option is to use them to represent only enums and not other data structures. 
  • Avoid automatic enums: TypeScript assigns values to the enum members if you don’t assign them explicitly. Give your enums values and avoid unexpected behavior when you execute your code. 
  • Document enums: Always document or comment on your code if you intend it to be consumed by the general public. Explain what every enum does and why is the best use case. 

You may also explore top TypeScript libraries and runtime to know as a developer.

Conclusion 

You can define enums in TypeScript and explain the different types and their use cases. TypeScript will come in handy when you want to have code clarity. However, there are also some cases where you should avoid them and use objects instead.

For instance, you should not use enums when dealing with dynamic values. You can also not use enums as variables; your program will return errors. 

You can learn more about the differences between TypeScript and JavaScript if you are still confused by the two.