Sometimes, we want to merge two enums in TypeScript.
In this article, we’ll look at how to merge two enums in TypeScript.
How to merge two enums in TypeScript?
To merge two enums in TypeScript, we can use the spread operator.
For instance, we write
enum Mammals {
Humans = "Humans",
Bats = "Bats",
Dolphins = "Dolphins",
}
enum Reptiles {
Snakes = "Snakes",
Alligators = "Alligators",
Lizards = "Lizards",
}
const Animals = { ...Mammals, ...Reptiles };
type Animals = typeof Animals;
to create the Mammals
and Reptiles
enums.
Then we combine them in the Animals
object by spreading the entries of Mammals
and Reptiles
into it.
And finally, we create the Animals
type by using the typeof
operator on Animals
.
Conclusion
To merge two enums in TypeScript, we can use the spread operator.