Discriminated Unions

In typescript you can check if a class is of a certain type with instanceof:

  if (animal instanceof Bird) {
    animal.fly();
  }

However, when using interfaces this will not work because javascript has no knownledge of interfaces.
A way to ‘solve’ this issue would be to add a dedicated property to the interface:

interface Bird {
  type: 'bird';
  fly: () => void;
}

interface Dog {
  type: 'dog';
  walk: () => void;
}

// The union consisting of the two interfaces
type Animal = Bird | Dog;

Now based on type we can create a switch (with some nice intellisense in our IDE):

const moveAnimal = (animal: Animal) => {
  switch (animal.type) {
    case 'bird':
      animal.fly();
      console.log('gone is our bird');
      break;
    case 'dog':
      animal.walk();
      console.log('walking our obedient friend');
      break;
    default:
      console.log('Unknown type');
  }
}