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. 😎😎
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Sign up for Infrastructure as a Newsletter.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.