Tutorial

TypeScript Enum Declaration and Merging

TypeScript

While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.

This is the second post on declaration merging in TypeScript. In the previous post, we looked at what declaration merging is and started with interfaces. In this post, we will look at how to merge enums.

For an introduction to Enums and why they are useful, you can read this post.

Let’s get started:

enum Department {
  IT, 
  Marketing
}

enum Department {
  HR
}

In our code above, since both enums have the same name, Department, TypeScript should be able to merge them, right? Well, not so fast! This will actually throw an error in the second enum declaration if we are to leave it like this. The error reads: In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element.

What this means is that, enum elements are automatically assigned values if not specified. So IT in the first Department enum is assigned the value 0 and Marketing is assigned the value of 1. In the second Department, since HR is the first element in that enum, it is also assigned the value of 0. When merged, both IT and HR will have a value of 0 and that is not permitted hence, the error.

To solve this, we can specify a value for the first element in our enum. Subsequent elements in the enum will have their values increased by one if not specified.

enum Department {
  IT = 1, 
  Marketing // has a value of 2, that is 1 + (IT value)
}

enum Department {
  HR // has an automatically assigned value of 0
}

console.log(Department[1]) // IT
console.log(Department[2]) // Marketing
console.log(Department[0]) // HR

By specifying the value of 1 to IT, when HR is automatically assigned the value of 0, it won’t cause any error because no other element has that value.

Of course, we can also assigned specific values to all the elements too.

enum Department {
  IT = 5, 
  Marketing = 3
}

enum Department {
  HR = 8
}

console.log(Department[5]) // IT
console.log(Department[3]) // Marketing
console.log(Department[8]) // HR

That’s it. 😎😎

Creative Commons License