Just Learn Code

Mastering Enums in TypeScript: Types Examples and Best Practices

Typescript is a popular programming language that has gained a lot of traction among developers in recent years. One of the powerful features of Typescript is its ability to use enums, which are a type of data structure that allows developers to define a set of named constants.

Enums can be extremely useful in programming, as they make code more readable, maintainable, and easy to understand. In this article, we will cover the different types of enums available in Typescript, including numeric enums, string-based enums, and multiple enums.

Numeric Enums in TypeScript

Numeric enums are one of the most commonly used types of enums in Typescript. As the name suggests, numeric enums use numeric values to define their set of named constants.

To define a numeric enum in Typescript, you can use the enum keyword, followed by the name of your enum, and a set of named constants. For example, let’s say we wanted to define a numeric enum that represents the days of the week.

We could do this as follows:

“`

enum DaysOfWeek {

Monday,

Tuesday,

Wednesday,

Thursday,

Friday,

Saturday,

Sunday

}

“`

In this example, we have defined an enum called DaysOfWeek that has named constants for each day of the week, starting with Monday and ending with Sunday. The first constant in a numeric enum always has a value of 0, and subsequent constants are assigned ordinal values starting from 1.

These ordinal values can also be set manually, as we will see in the next example.

Enum instance with initialized variables

When defining a numeric enum, you can also assign specific values to the named constants. For example, let’s say we wanted to define a numeric enum that represents the sizes of shirts:

“`

enum ShirtSize {

Small = 1,

Medium,

Large,

XL,

XXL

}

“`

In this example, we have defined an enum called ShirtSize that has named constants for each size of a shirt.

The first constant, Small, is assigned a value of 1, and subsequent constants are assigned ordinal values starting from 2. By assigning specific values to the named constants, you can create more meaningful and customized enums that better suit your programming needs.

String-Based Enums in TypeScript

String-based enums are another type of enum available in Typescript. Unlike numeric enums, which use numeric values to define their named constants, string-based enums use strings.

To define a string-based enum in Typescript, you can use the enum keyword, followed by the name of your enum, and a set of named constants. For example, let’s say we wanted to define a string-based enum that represents the colors of the rainbow:

“`

enum RainbowColors {

Red = “red”,

Orange = “orange”,

Yellow = “yellow”,

Green = “green”,

Blue = “blue”,

Indigo = “indigo”,

Violet = “violet”

}

“`

In this example, we have defined an enum called RainbowColors that has named constants for each color of the rainbow, represented as strings.

String-based enums can be particularly useful when you are working with data that is better represented as text strings, rather than numeric values.

Enum instance with undefined variables

When defining a string-based enum, you can also leave the named constants undefined. For example, let’s say we wanted to define a string-based enum that represents the different types of animals:

“`

enum AnimalTypes {

Mammal,

Reptile,

Amphibian,

Bird,

Fish,

Insect,

Arachnid

}

“`

In this example, we have defined an enum called AnimalTypes that has named constants for each type of animal.

By leaving the constants undefined, we can assign them later as needed, making string-based enums more flexibile and dynamic than their numeric counterparts.

Multiple Enums in TypeScript

Finally, it is also possible to define multiple enums in a single Typescript file. This can be useful when you have separate sets of named constants that represent different aspects of your coding needs.

For example, let’s say we wanted to define both a numeric enum for the days of the week and a string-based enum for the months of the year:

“`

enum DaysOfWeek {

Monday,

Tuesday,

Wednesday,

Thursday,

Friday,

Saturday,

Sunday

}

enum MonthsOfYear {

January = “jan”,

February = “feb”,

March = “mar”,

April = “apr”,

May = “may”,

June = “jun”,

July = “jul”,

August = “aug”,

September = “sep”,

October = “oct”,

November = “nov”,

December = “dec”

}

“`

In this example, we have defined two separate enums, one for the days of the week and another for the months of the year. By separating our different data sets into separate enums, we can keep our code organized and easy to manage.

Conclusion

In this article, we have covered the different types of enums available in Typescript, including numeric enums, string-based enums, and multiple enums. Enums can be a powerful tool for developers, allowing them to define sets of named constants that can make code more readable, maintainable, and easy to understand.

Whether you are working with numeric or text-based data, using enums can help you write better code and create more effective programs.

3) Example of String-Based Enums

String-based enums are an excellent choice when you need to represent data that can be better articulated as a text string. You can define a string-based enum by using the `enum` keyword, followed by the name of the enum and a set of named constants that are represented as strings.

Enum instance with initialized variables

As with numeric enums, you can also initialize variables in a string-based enum. This is shown in the following example, which represents a list of different types of fruits:

“`

enum FruitsEnum {

Apple = “apple”,

Banana = “banana”,

Cherry = “cherry”,

Date = “date”,

Elderberry = “elderberry”,

}

“`

Here, we have defined a string-based enum called `FruitsEnum`, which includes several named constants.

These named constants represent different types of fruits and are represented as strings. You can then use the named constants later in your code by calling them from the enum.

Enum instance with undefined variables

As with numeric enums, you can also define an empty string-based enum and initialize the named constants later in your code. This can be useful when you are unsure of what named constants you will need to use when you initially define the enum.

“`

enum CarMakerEnum {

Sedan = “”,

Coupe = “”,

Wagon = “”,

}

CarMakerEnum.Sedan = “Ford”;

CarMakerEnum.Coupe = “Mazda”;

CarMakerEnum.Wagon = “Subaru”;

“`

Here, we defined an empty string-based enum called `CarMakerEnum` that includes three named constants. We can then initialize them later in our code.

It’s worth noting that if you try to initialize an undefined string-based enum and don’t assign values to the named constants later, you will get an error message. This tells you that your named constants need to be assigned values before they can be used in your code.

4)

Multiple Enums in TypeScript

Multiple enums can be a powerful tool for organizing your code and keeping your data types separate. You can define separate enums for different types of data to help you better organize your code and make it more readable.

Good practice to separate data types

Separating your data types into different enums is a best practice for writing clean, readable code. For example, you might want to have one enum for user roles and another for different types of products.

This separation helps you keep your code organized and makes it easier to maintain and make changes later on. “`

enum ProductType {

Electronic,

Furniture,

Books,

Clothing,

}

enum UserRole {

Admin,

Manager,

Salesperson,

Customer,

}

“`

Here, we have defined two separate enums: one for product types and the other for user roles.

Separating them in this way can make it easier to read and understand the code.

Bad use of enum data type

However, multiple enums can also be misused if you have multiple enums that represent the same type of data. For example, you might have one enum that represents different types of colors and another that represents shades of the same color.

This can cause confusion and make your code harder to read and maintain. “`

enum RainbowColors {

Red,

Orange,

Yellow,

Green,

Blue,

Indigo,

Violet,

}

enum ShadesOfRed {

LightRed,

MediumRed,

DarkRed,

}

“`

In this example, we have defined two separate enums `RainbowColors` and `ShadesOfRed`.

Although they are both related to colors, they are not interchangeable. This can lead to confusion and errors if you use the wrong enum for a specific data type.

You should avoid creating multiple enums that represent the same type of data. If you find yourself in this situation, it’s better to merge the enums or refactor them to better suit your needs.

Conclusion

Enums can be a powerful tool for organizing and maintaining code in Typescript. By defining named constants that represent different types of data, you can make your code more readable, efficient, and maintainable.

It’s essential to use good coding practices when defining enums, which means separating them for different data types and avoiding using multiple enums to represent the same data type. With these best practices in mind, enums can be a valuable tool for any Typescript developer.

In summary, enums are an essential feature in Typescript that allow developers to define sets of named constants for different data types. Numeric enums use ordinal values, while string-based enums use text strings for the named constants.

Multiple enums can be useful for separating different data types in your code. However, it is crucial to avoid using multiple enums for the same data type to avoid confusion and errors.

Good coding practices that involve separating different data types and using enums appropriately can increase code readability, maintainability, and efficiency. Therefore, understanding and managing enums in Typescript is an essential skill for developers looking to create efficient and maintainable code.

Popular Posts