TypeScript also provides C#-style enum types:
enum YesNoAnswer { unknown, yes, no};
var myAnswer: YesNoAnswer = YesNoAnswer.unknown;
Like in C#, enum values are translated into integers. As a default, the first value is assigned 0, the second value 1, and so on. However, the default start value may be changed:
enum YesNoAnswer { unknown=1, yes , no}; //yes=2, no=3
You may also provide default integers for all enum values:
enum YesNoAnswer { unknown=1, yes=3 , no=5};
Integers may also be specified through expressions involving the previously defined variables and values of the same enum:
enum YesNoAnswer { unknown=1, yes=unknown+2 , no=yes+2};
The TypeScript compiler generates a variable with the same name as the enum and does something like this:
YesNoAnswer = {};
YesNoAnswer["unknown"] = 1;
YesNoAnswer["yes"] = 3;
YesNoAnswer["no"] = 5;
That's why we may use expressions such as YesNoAnswer.unknown to refer to the enum values.
We may also translate the integer associated with each enum value to the string representing its name:
>YesNoAnswer[3]
>"yes"
This is because the TypeScript compiler generates also something like:
YesNoAnswer[1] = "unknown";
YesNoAnswer[3] = "yes";
YesNoAnswer[5] = "no";
If the enum is defined to be constant, the YesNoAnswer variable and all associated properties are not generated, and each occurrence of YesNoAnswer.unknown, YesNoAnswer.yes, and YesNoAnswer.no in the code is replaced by its associated integer at compile time in the generated JavaScript code:
const enum YesNoAnswer { unknown=1, yes=3 , no=5};
var myAnswer: YesNoAnswer = YesNoAnswer.unknown;
/* when the enum is const this is wrong*/
var valueName: string = YesNoAnswer[1];
However, in this case, expressions like YesNoAnswer[3] are not allowed anymore:
Moreover, all integers defining the constant enum values must be constant the compiler may compute at compile time.
Thus, the following is correct:
const enum YesNoAnswer { unknown=1, yes=unknown+2 , no=yes+2};
However, we can't assign the startEnum variable, whose value changes at runtime, to unknown:
var startEnum : number;
...
...
...
const enum YesNoAnswer { unknown=startEnum, yes=unknown+2 , no=yes+2};
Otherwise, we get a compilation error:
Thus, const enum generates less JavaScript code at the price of less flexibility.
enum values may be combined with the bitwise operators &, |, and ~:
const enum YesNoAnswer { unknown = 1, yes = unknown + 2, no = yes + 2 };
var myAnswer: YesNoAnswer = YesNoAnswer.unknown | YesNoAnswer.yes;
Thus, we may define the equivalent of C# bit flags:
const enum TextTransformation {
None = 0,
Bold = 1,
Italic = Bold << 1, //2
Underline = Italic << 1, //4
Overline = Italic << 1, //8
LineThrough = Overline << 1, // 16
HasLine = Underline | Overline | LineThrough
}
function HasBold(x: TextTransformation): boolean {
return (x & TextTransformation.Bold) == TextTransformation.Bold;
}
The HasBold function shows how bit properties may be tested in exactly the same way as in C#.