Enums

An enum is a way to organize a collection of related values. Many other programming languages (C/C#/Java) have an enum data type but JavaScript does not. However TypeScript does. Here is an example definition of a TypeScript enum:

  1. enum CardSuit {
  2. Clubs,
  3. Diamonds,
  4. Hearts,
  5. Spades
  6. }
  7. // Sample usage
  8. var card = CardSuit.Clubs;
  9. // Safety
  10. card = "not a member of card suit"; // Error : string is not assignable to type `CardSuit`

Enums and Numbers

TypeScript enums are number based. This means that numbers can be assigned to an instance of the enum, and so can anything else that is compatible with number.

  1. enum Color {
  2. Red,
  3. Green,
  4. Blue
  5. }
  6. var col = Color.Red;
  7. col = 0; // Effectively same as Color.Red

Enums and Strings

Before we look further into enums let’s look at the JavaScript that it generates, here is a sample TypeScript:

  1. enum Tristate {
  2. False,
  3. True,
  4. Unknown
  5. }

generates the following JavaScript:

  1. var Tristate;
  2. (function (Tristate) {
  3. Tristate[Tristate["False"] = 0] = "False";
  4. Tristate[Tristate["True"] = 1] = "True";
  5. Tristate[Tristate["Unknown"] = 2] = "Unknown";
  6. })(Tristate || (Tristate = {}));

let’s focus on the line Tristate[Tristate["False"] = 0] = "False";. Within it Tristate["False"] = 0 should be self explanatory, i.e. sets "False" member of Tristate variable to be 0. Note that in JavaScript the assignment operator returns the assigned value (in this case 0). Therefore the next thing executed by the JavaScript runtime is Tristate[0] = "False". This means that you can use the Tristate variable to convert a string version of the enum to a number or a number version of the enum to a string. This is demonstrated below:

  1. enum Tristate {
  2. False,
  3. True,
  4. Unknown
  5. }
  6. console.log(Tristate[0]); // "False"
  7. console.log(Tristate["False"]); // 0
  8. console.log(Tristate[Tristate.False]); // "False" because `Tristate.False == 0`

Changing the number associated with an Enum

By default enums are 0 based and then each subsequent value increments by 1 automatically. As an example consider the following:

  1. enum Color {
  2. Red, // 0
  3. Green, // 1
  4. Blue // 2
  5. }

However you can change the number associated with any enum member by assigning to it specifically. This is demonstrated below where we start at 3 and start incrementing from there:

  1. enum Color {
  2. DarkRed = 3, // 3
  3. DarkGreen, // 4
  4. DarkBlue // 5
  5. }

TIP: I quite commonly initialize the first enum with = 1 as it allows me to do a safe truthy check on an enum value.

Enums as flags

One excellent use of enums is the ability to use enums as Flags. Flags allow you to check if a certain condition from a set of conditions is true. Consider the following example where we have a set of properties about animals:

  1. enum AnimalFlags {
  2. None = 0,
  3. HasClaws = 1 << 0,
  4. CanFly = 1 << 1,
  5. EatsFish = 1 << 2,
  6. Endangered = 1 << 3
  7. }

Here we are using the left shift operator to move 1 around a certain level of bits to come up with bitwise disjoint numbers 0001, 0010, 0100 and 1000 (these are decimals 1,2,4,8 if you are curious). The bitwise operators | (or) / & (and) / ~ (not) are your best friends when working with flags and are demonstrated below:

  1. enum AnimalFlags {
  2. None = 0,
  3. HasClaws = 1 << 0,
  4. CanFly = 1 << 1,
  5. }
  6. function printAnimalAbilities(animal) {
  7. var animalFlags = animal.flags;
  8. if (animalFlags & AnimalFlags.HasClaws) {
  9. console.log('animal has claws');
  10. }
  11. if (animalFlags & AnimalFlags.CanFly) {
  12. console.log('animal can fly');
  13. }
  14. if (animalFlags == AnimalFlags.None) {
  15. console.log('nothing');
  16. }
  17. }
  18. var animal = { flags: AnimalFlags.None };
  19. printAnimalAbilities(animal); // nothing
  20. animal.flags |= AnimalFlags.HasClaws;
  21. printAnimalAbilities(animal); // animal has claws
  22. animal.flags &= ~AnimalFlags.HasClaws;
  23. printAnimalAbilities(animal); // nothing
  24. animal.flags |= AnimalFlags.HasClaws | AnimalFlags.CanFly;
  25. printAnimalAbilities(animal); // animal has claws, animal can fly

Here:

  • we used |= to add flags
  • a combination of &= and ~ to clear a flag
  • | to combine flags

Note: you can combine flags to create convenient shortcuts within the enum definition e.g. EndangeredFlyingClawedFishEating below:

  1. enum AnimalFlags {
  2. None = 0,
  3. HasClaws = 1 << 0,
  4. CanFly = 1 << 1,
  5. EatsFish = 1 << 2,
  6. Endangered = 1 << 3,
  7. EndangeredFlyingClawedFishEating = HasClaws | CanFly | EatsFish | Endangered,
  8. }

Const Enums

If you have an enum definition like the following:

  1. enum Tristate {
  2. False,
  3. True,
  4. Unknown
  5. }
  6. var lie = Tristate.False;

The line var lie = Tristate.False is compiled to the JavaScript var lie = Tristate.False (yes, output is same as input). This means that at execution the runtime will need to lookup Tristate and then Tristate.False. To get a performance boost here you can mark the enum as a const enum. This is demonstrated below:

  1. const enum Tristate {
  2. False,
  3. True,
  4. Unknown
  5. }
  6. var lie = Tristate.False;

generates the JavaScript:

  1. var lie = 0;

i.e. the compiler:

  1. Inlines any usages of the enum (0 instead of Tristate.False).
  2. Does not generate any JavaScript for the enum definition (there is no Tristate variable at runtime) as its usages are inlined.
Const enum preserveConstEnums

Inlining has obvious performance benefits. The fact that there is no Tristate variable at runtime is simply the compiler helping you out by not generating JavaScript that is not actually used at runtime. However you might want the compiler to still generate the JavaScript version of the enum definition for stuff like number to string or string to number lookups as we saw. In this case you can use the compiler flag --preserveConstEnums and it will still generate the var Tristate definition so that you can use Tristate["False"] or Tristate[0] manually at runtime if you want. This does not impact inlining in any way.

Enum with static functions

You can use the declaration enum + namespace merging to add static methods to an enum. The following demonstrates an example where we add a static member isBusinessDay to an enum Weekday:

  1. enum Weekday {
  2. Monday,
  3. Tuesday,
  4. Wednesday,
  5. Thursday,
  6. Friday,
  7. Saturday,
  8. Sunday
  9. }
  10. namespace Weekday {
  11. export function isBusinessDay(day: Weekday) {
  12. switch (day) {
  13. case Weekday.Saturday:
  14. case Weekday.Sunday:
  15. return false;
  16. default:
  17. return true;
  18. }
  19. }
  20. }
  21. const mon = Weekday.Monday;
  22. const sun = Weekday.Sunday;
  23. console.log(Weekday.isBusinessDay(mon)); // true
  24. console.log(Weekday.isBusinessDay(sun)); // false

Enums are open ended

NOTE: open ended enums are only relevant if you are not using modules. You should be using modules. Hence this section is last.

Here is the generated JavaScript for an enum shown again:

  1. var Tristate;
  2. (function (Tristate) {
  3. Tristate[Tristate["False"] = 0] = "False";
  4. Tristate[Tristate["True"] = 1] = "True";
  5. Tristate[Tristate["Unknown"] = 2] = "Unknown";
  6. })(Tristate || (Tristate = {}));

We already explained the Tristate[Tristate["False"] = 0] = "False"; portion. Now notice the surrounding code (function (Tristate) { /*code here */ })(Tristate || (Tristate = {})); specifically the (Tristate || (Tristate = {})); portion. This basically captures a local variable TriState that will either point to an already defined Tristate value or initialize it with a new empty {} object.

This means that you can split (and extend) an enum definition across multiple files. For example below we have split the definition for Color into two blocks

  1. enum Color {
  2. Red,
  3. Green,
  4. Blue
  5. }
  6. enum Color {
  7. DarkRed = 3,
  8. DarkGreen,
  9. DarkBlue
  10. }

Note that you should reinitialize the first member (here DarkRed = 3) in a continuation of an enum to get the generated code not clobber values from a previous definition (i.e. the 0, 1, … so on values). TypeScript will warn you if you don’t anyways (error message In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element.).