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 ?
CodePudding user response:
There is no pattern matching syntax in JavaScript, so there is no such syntax in TypeScript either (as that would be runtime syntax and TypeScript no longer adds that, it relies on additions to JavaScript)
You can use type guards. If you are dealing with classes, the best type guard to use is instanceof.
let l = [new Cat(), new Dog()];
l.map((a:Animal) =>
a instanceof Dog ? a.isGoodBoy() :
a instanceof Cat ? a.sayName():
a.speak())
