1.7 Enum Types
TypeScript enables programmers to summarize a set of numeric constants as an enum type. The example below creates an enum type to represent operators in a calculator application.
const enum Operator {
ADD,
DIV,
MUL,
SUB
}
function compute(op: Operator, a: number, b: number) {
console.log("the operator is" + Operator[op]);
// ...
}
In this example, the compute function logs the operator ‘op’ using a feature of enum types: reverse mapping from the enum value (‘op’) to the string corresponding to that value. For example, the declaration of ‘Operator’ automatically assigns integers, starting from zero, to the listed enum members. Section 9 describes how programmers can also explicitly assign integers to enum members, and can use any string to name an enum member.
When enums are declared with the const
modifier, the TypeScript compiler will emit for an enum member a JavaScript constant corresponding to that member’s assigned value (annotated with a comment). This improves performance on many JavaScript engines.
For example, the ‘compute’ function could contain a switch statement like the following.
switch (op) {
case Operator.ADD:
// execute add
break;
case Operator.DIV:
// execute div
break;
// ...
}
For this switch statement, the compiler will generate the following code.
switch (op) {
case 0 /* Operator.ADD */:
// execute add
break;
case 1 /* Operator.DIV */:
// execute div
break;
// ...
}
JavaScript implementations can use these explicit constants to generate efficient code for this switch statement, for example by building a jump table indexed by case value.