Suppose I have two enums as described below in Typescript, then How do I merge them
enum Mammals {
Humans,
Bats,
Dolphins
}
enum Reptiles {
What's confusing here is types vs. values.
let
, const
etc.) it will have a value plus some computed but not separately named type.type
or interface
, it will create a named type but that will not be outputted or considered in the final JS in any way. It only helps when writing your app.From the TS handbook:
Using an enum is simple: just access any member as a property off of the enum itself, and declare types using the name of the enum.
So, if you Object.assign()
two enums, it will create a new, merged value (object), but not a new named type.
Since it's not an enum
anymore, you lose the advantage of having a value and a named type, but you can still create a separate type name as a workaround.
Fortunately, you can have the same name for the value and the type, and TS will import both if you export them.
// This creates a merged enum, but not a type
const Animals = Object.assign({}, Mammals, Reptiles);
// Workaround: create a named type (typeof Animals won't work here!)
type Animals = Mammals | Reptiles;
TS playground link