TypeScript enums are a special class con­sist­ing of constant variables. You can define the value of these variables in advance. A dis­tinc­tion is made between numeric and string-based enums.

What are TypeScript enums?

Enums (short for ‘enu­mer­ated types’) are data types that have a finite set of values. This set of values is already clearly defined during the de­clar­a­tion of an enum with an iden­ti­fi­er and cannot be changed af­ter­wards. The order in which the values may appear can also be defined in advance. With TypeScript enums, you can create constant variables that increase the read­ab­il­ity of your code and at the same time avoid errors. This is one of the few features that is not a stat­ic­ally typed extension of JavaS­cript. A dis­tinc­tion is made between numeric and string-based TypeScript enums. We will introduce you to both variants.

Managed Nextcloud from IONOS Cloud
Work together in your own cloud
  • Industry-leading security
  • Com­mu­nic­a­tion and col­lab­or­a­tion tools
  • Hosted and developed in Europe

Numeric TypeScript enums

In numeric TypeScript enums, the initial value is set to ‘0’ by default, and each following value is auto­mat­ic­ally in­cre­men­ted by ‘1’. The method is ini­tial­ised with the enum parameter and stores strings as numeric values. In a basic example, we define the months and assign a value to each one. Afterward, we retrieve the value assigned to the month of April:

enum Months {
	January,
	February,
	March,
	April,
	May,
	June,
	July,
	August,
	September,
	October,
	November,
	December
}
let currentMonth = Months.April;
console.log(currentMonth);
typescript

The output looks like this:

3
typescript

The system begins assigning values by default starting from ‘0’, meaning January is assigned ‘0’, February ‘1’, March ‘2’, and April, receives the value, ‘3’. Since this doesn’t match the actual month numbering, we ini­tial­ise the TypeScript enums and manually assign the correct values. To achieve this, we only need to make minor ad­just­ments to the code above:

enum Months {
	January = 1,
	February,
	March,
	April,
	May,
	June,
	July,
	August,
	September,
	October,
	November,
	December
}
let currentMonth = Months.April;
console.log(currentMonth);
typescript

Now the output looks like this:

4
typescript

You only need to set the desired value for the first month. After that, the system will auto­mat­ic­ally continue counting by one as usual.

Assign your own numeric values

To override the automatic numbering, you can assign custom numeric values to each element in a TypeScript enum. In the following example, we have four volumes of a book series and aim to store their re­spect­ive page counts as fixed values. Then, to verify, we’ll display the page count for the second volume. The code would look like this:

enum PageNumber {
	Volume1 = 491,
	Volume2 = 406,
	Volume3 = 360,
	Volume4 = 301
}
let pages = PageNumber.Volume2;
console.log(pages);
typescript

The output would be:

406
typescript

String-based TypeScript enums

String-based TypeScript enums function in a similar manner. However, instead of assigning numerical values, you assign strings to the enums. In the example below, each day of the week is given a cor­res­pond­ing ab­bre­vi­ation in string format, enclosed in quotation marks. We then retrieve the values for ‘Friday’ and ‘Tuesday’ to verify the output. Here’s the code:

enum WeekDays {
Monday = "Mo",
Tuesday = "Tu",
Wednesday = "We",
Thursday = "Th",
Friday = "Fr",
Saturday = "Sa",
Sunday = "Su"
};
console.log(WeekDays.Friday);
console.log(WeekDays.Tuesday);
typescript

The output for this is:

Fr
Tu
typescript

Combining numbers and strings

It’s also possible to combine numeric and string-based TypeScript enums, although the use cases for this approach are fairly limited. However, for the sake of com­plete­ness, we’ll provide an example. In this case, we define different values, but the process itself remains unchanged:

enum WeekDays {
Monday = "Mo",
Tuesday = 2,
Wednesday = 3,
Thursday = "Th",
Friday = "Fr",
Saturday = 6,
Sunday = "Su"
};
console.log(WeekDays.Friday);
console.log(WeekDays.Tuesday);
typescript

The output now reads as follows:

Fr
2
typescript

Reverse mapping for constant data types

The concept of Reverse Mapping means that if you can access the value of a TypeScript enum, you can also retrieve its cor­res­pond­ing name. To demon­strate this principle, let’s revisit our example with the days of the week:

enum WeekDays {
Monday = 1,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
};
WeekDays.Friday
WeekDays["Friday"];
WeekDays[5];
typescript

In this example, WeekDays.Friday outputs the value ‘5’, as does WeekDays[“Friday”]. Thanks to reverse mapping, however, WeekDays[5] will return the name ‘Friday’. This can be il­lus­trated with the following simple command:

enum WeekDays {
Monday = 1,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
};
console.log(WeekDays);
typescript

This gives us the following output:

{
    '1': 'Monday',
    '2': 'Tuesday',
    '3': 'Wednesday',
    '4': 'Thursday',
    '5': 'Friday',
    '6': 'Saturday',
    '7': 'Sunday',
    Monday: 1,
    Tuesday: 2,
    Wednesday: 3,
    Thursday: 4,
    Friday: 5,
    Saturday: 6,
    Sunday: 7
}
typescript

Convert TypeScript enums to array

It is also possible to convert TypeScript enums into TypeScript arrays. For our example using the days of the week, the code looks like this:

enum WeekDays {
Monday = "Mo",
Tuesday = "Tu",
Wednesday = "We",
Thursday = "Th",
Friday = "Fr",
Saturday = "Sa",
Sunday = "Su"
};
const weekdaysArray: { label: string; value: string }[] = [];
for (const key in WeekDays) {
    if (WeekDays.hasOwnProperty(key)) {
        weekdaysArray.push({ label: key, value: WeekDays[key] });
    }
}
console.log(weekdaysArray);
typescript

This is how we get this output:

[
    { label: 'Monday', value: 'Mo' },
    { label: 'Tuesday', value: 'Tu' },
    { label: 'Wednesday', value: 'We' },
    { label: 'Thursday', value: 'Th' },
    { label: 'Friday', value: 'Fr' },
    { label: 'Saturday', value: 'Sa' },
    { label: 'Sunday', value: 'Su' }
]
typescript
Tip

Deploy your static website or app directly via GitHub! With Deploy Now from IONOS, you benefit from a quick setup, optimised workflows and various pricing models. Find the solution that best suits your project!

Go to Main Menu