That's because in TypeScript Enums are open ended.
This means that you can do something like below:
enum Colors {
Red,
Green,
Blue
}
console.log(Colors); // { '0': 'Red', '1': 'Green', '2': 'Blue', Red: 0, Green: 1, Blue: 2 }
enum Colors {
Black = 3,
White
}
console.log(Colors); // { '0': 'Red', '1': 'Green', '2': 'Blue', '3': 'Black', '4': 'White', Red: 0, Green: 1, Blue: 2, Black: 3, White: 4 }
That means that you can add new members to an already defined enum
. Consider this as partial class in C# or interface
s in typescript.
The IIFE is used so that any existing definition (read object) of enum
of the same name can be picked up.
Also TypeScript correctly shows reports the below error if we omit = 3
part from the second enum Colors
definition.
In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element.
(enum member) Colors.Black = 0
Read more here: https://basarat.gitbooks.io/typescript/docs/enums.html
EDIT: Also note that there are some benefit of using IIFE.
- Local scope optimization: It is always beneficial to declare your variable as close as possible to your first use of that variable. JavaScript can traverse from local scope to global scope in order to lookup a variable. Thus, using a local variable can provide performance benefit.
Minification: this is already mentioned in the answer by @Piotr Kocia. It means that you can also use shorter variable names for the IIFE.
var Colors;
(function (C) {
C[C["Red"] = 0] = "Red";
C[C["Green"] = 1] = "Green";
C[C["Blue"] = 2] = "Blue";
})(Colors || (Colors = {}));
This might not look a so lucrative proposition at this point but consider when you variable name is longer.
More on the topic "Why IIFE": http://gregfranko.com/blog/i-love-my-iife/
Hope this helps.