When multiple enums of the same name exist in the same module, TypeScript merges them into a single enum automatically:
enum Direction { Up = "UP", Down = "DOWN", } enum Direction { Left = "LEFT", Right = "RIGHT", } const dir1: Direction = Direction.Up; // "UP" const dir2: Direction = Direction.Left; // "LEFT" // ...
This will compile into the following JavaScript code at runtime:
var Direction; (function (Direction) { Direction["Up"] = "UP"; Direction["Down"] = "DOWN"; })(Direction || (Direction = {})); (function (Direction) { Direction["Left"] = "LEFT"; Direction["Right"] = "RIGHT"; })(Direction || (Direction = {}));
If you declare multiple enums of the same name, then only one declaration can omit an initializer for its first enum element, otherwise a compile-time error will be thrown:
enum Color { Red, Green, Blue, } enum Color { // Error: In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element. Yellow, Cyan, } enum Color { // Error: In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element. Pink, Orange, }
To avoid this error, it is necessary to ensure that only one of the merging enums is without an initializer:
enum Color { Red, Green, Blue, } enum Color { Yellow = 0, Cyan, } enum Color { Pink = 5, Orange, } const color1: Color = Color.Red; // 0 const color2: Color = Color.Green; // 1 // ... const color3: Color = Color.Yellow; // 0 const color4: Color = Color.Cyan; // 1 // ... const color5: Color = Color.Pink; // 5 const color6: Color = Color.Orange; // 6
As you can see in the example above, it is possible for merging enum members that have the same initializers.
This will compile into the following JavaScript code at runtime:
var Color; (function (Color) { Color[Color["Red"] = 0] = "Red"; Color[Color["Green"] = 1] = "Green"; Color[Color["Blue"] = 2] = "Blue"; })(Color || (Color = {})); (function (Color) { Color[Color["Yellow"] = 0] = "Yellow"; Color[Color["Cyan"] = 1] = "Cyan"; })(Color || (Color = {})); (function (Color) { Color[Color["Pink"] = 5] = "Pink"; Color[Color["Orange"] = 6] = "Orange"; })(Color || (Color = {}));
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.