A good use for enumerations is as a flag to check whether a condition in a set of conditions is true.

Take animals as an example:


enum AnimalFlags {
    None        = 0,
    HasClaws    = 1 << 0,
    CanFly      = 1 << 1,
    EatsFish    = 1 << 2,
    Endangered  = 1 << 3,}Copy the code

We use the left-shift operator here to get the binary digits 0001, 0010, 0100, 1000 (corresponding to decimal 1,2,4, 8) respectively. With an operator |, &, ~ can be made to the operation of the logo (add, remove, check) became very friendly.

Here’s an example:

enum AnimalFlags {
    None        = 0,
    HasClaws    = 1 << 0,
    CanFly      = 1 << 1,
    EatsFish    = 1 << 2,
    Endangered  = 1 << 3,}interface Animal {
    flags: AnimalFlags;
}

function printAnimalAbilities(animal: Animal) {
  const animalFlags = animal.flags;
  // & Check to see if flags exist
  if (animalFlags & AnimalFlags.HasClaws) {
    console.log('animal has claws');
  }
  if (animalFlags & AnimalFlags.CanFly) {
    console.log('animal can fly');
  }
  if (animalFlags === AnimalFlags.None) {
    console.log('nothing'); }}const animal: Animal = { flags: AnimalFlags.None };
printAnimalAbilities(animal); // nothing

// Add the CanFly flag
animal |= AnimalFlags.CanFly;
printAnimalAbilities(animal); // animal can fly

// Remove the CanFly flag
animal &= ~AnimalFlags.CanFly;
printAnimalAbilities(animal); // nothing

/ / merge add Canfly and HasClwas marks (essentially two | =)
animal |= AnimalFlags.CanFly | AnimalFlags.HasClaws;
printAnimalAbilities(animal); // animal has claws\n animal can fly


Copy the code

Conclusion:

  1. Generate binary flag bit with left shift operator;
  2. use| =Add a flag;
  3. use&Check whether a flag exists;
  4. Together with& =~Remove a sign;