Suppose I have two enums as described below in Typescript, then How do I merge them
enum Mammals {
Humans,
Bats,
Dolphins
}
enum Reptiles {
A TypeScript enum not only contains the keys you define but also the numerical inverse, so for example:
Mammals.Humans === 0 && Mammals[0] === 'Humans'
Now, if you try to merge them -- for example with Object#assign
-- you'd end up with two keys having the same numerical value:
const AnimalTypes = Object.assign({}, Mammals, Reptiles);
console.log(AnimalTypes.Humans === AnimalTypes.Snakes) // true
And I suppose that's not what you want.
One way to prevent this, is to manually assign the values to the enum and make sure that they are different:
enum Mammals {
Humans = 0,
Bats = 1,
Dolphins = 2
}
enum Reptiles {
Snakes = 3,
Alligators = 4,
Lizards = 5
}
or less explicit but otherwise equivalent:
enum Mammals {
Humans,
Bats,
Dolphins
}
enum Reptiles {
Snakes = 3,
Alligators,
Lizards
}
Anyway, as long as you make sure that the enums you merge have different key/value sets you can merge them with Object#assign
.
Playground Demo