'Pattern matching in Typescript over subclasses

Assume the following type hierarchy:

interface Animal {
   //...
}

class Dog implements Animal {
   //...
}

class Cat implements Animal {
  //...
}

Now, I have a variable let l:Array<Animal> = [new Dog(...),new Cat(...)] somwhere in my code, and I want to map over that array and perform different operations depending on whether i look at a Dog instance or a Cat instance, and in ideal case using a procedure such as pattern matching. I am thinking of pattern matching in other functional languages such as Scala or Haskell:

l.map((a:Animal) => match a {case Cat => ..., case Dog => ... })

Which ways are there to code/emulate a pattern match like this over subtypes in TypeScript ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source