# How to use TypeScript enums to define constant values for variables

TypeScript enums are a special class consisting of constant variables. You can define the value of these variables in advance. A distinction is made between numeric and string-based enums.

## What are TypeScript enums?

Enums (short for ‘enumerated types’) are data types that have a **finite set of values**. This set of values is already clearly defined during the declaration of an enum with an identifier and cannot be changed afterwards. The order in which the values may appear can also be defined in advance. With [TypeScript](https://www.ionos.co.uk/digitalguide/websites/web-development/what-is-typescript/) enums, you can create constant variables that increase the **readability of your code** and at the same time **avoid errors**. This is one of the few features that is not a statically typed extension of JavaScript. A distinction is made between **numeric and string-based TypeScript enums**. We will introduce you to both variants.

## Numeric TypeScript enums

In numeric TypeScript enums, the initial value is set to ‘0’ by default, and each following value is automatically incremented by ‘1’. The method is initialised 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:

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

The output looks like this:

```typescript
3
```

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 initialise the TypeScript enums and **manually assign the correct values**. To achieve this, we only need to make minor adjustments to the code above:

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

Now the output looks like this:

```typescript
4
```

You only need to set the desired value for the first month. After that, the system will automatically 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 respective page counts as fixed values. Then, to verify, we’ll display the page count for the second volume. The code would look like this:

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

The output would be:

```typescript
406
```

## 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 corresponding abbreviation in string format, enclosed in quotation marks. We then retrieve the values for ‘Friday’ and ‘Tuesday’ to verify the output. Here’s the code:

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

The output for this is:

```typescript
Fr
Tu
```

## 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 completeness, we’ll provide an example. In this case, we define different values, but the process itself remains unchanged:

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

The output now reads as follows:

```typescript
Fr
2
```

## 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 corresponding name. To demonstrate this principle, let’s revisit our example with the days of the week:

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

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 illustrated with the following simple command:

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

This gives us the following output:

```typescript
{
    '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
}
```

## Convert TypeScript enums to array

It is also possible to convert TypeScript enums into [TypeScript arrays](https://www.ionos.co.uk/digitalguide/websites/web-development/typescript-arrays/). For our example using the days of the week, the code looks like this:

```typescript
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);
```

This is how we get this output:

```typescript
[
    { 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' }
]
```

Tip Deploy your static website or app directly via GitHub! With [Deploy Now](https://www.ionos.co.uk/hosting/deploy-now "Deploy Now from IONOS") from IONOS, you benefit from a quick setup, optimised workflows and various pricing models. Find the solution that best suits your project!


This is a markdown version of: [https://www.ionos.co.uk/digitalguide/websites/web-development/typescript-enums/](https://www.ionos.co.uk/digitalguide/websites/web-development/typescript-enums/) for AI/LLM consumption.