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.

  1. const enum Operator {
  2. ADD,
  3. DIV,
  4. MUL,
  5. SUB
  6. }
  7. function compute(op: Operator, a: number, b: number) {
  8. console.log("the operator is" + Operator[op]);
  9. // ...
  10. }

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.

  1. switch (op) {
  2. case Operator.ADD:
  3. // execute add
  4. break;
  5. case Operator.DIV:
  6. // execute div
  7. break;
  8. // ...
  9. }

For this switch statement, the compiler will generate the following code.

  1. switch (op) {
  2. case 0 /* Operator.ADD */:
  3. // execute add
  4. break;
  5. case 1 /* Operator.DIV */:
  6. // execute div
  7. break;
  8. // ...
  9. }

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.