I have two classes:
class Dog {
run() {
console.log("RUN")
}
}
class Fish {
swim() {
console.log("SWIM")
}
}
I then make a type union through:
type Pet = Dog | Fish
I then use a type predicate to evaluate what is the superclass of Pet instances:
function isDog(pet: Pet): pet is Dog {
return (pet as Dog).run !== undefined
}
function isFish(pet: Pet): pet is Fish {
return (pet as Fish).swim !== undefined
}
I then have an array of Pets:
const zoo: Array<Pet> = [dog, dog, dog, fish, fish, fish]
I would like to filter the array having only Fish instances, I do:
const underwater: Array<Fish> = zoo.filter(isFish)
which works.
Why doesn't this work in the 'expanded' version of the filter function?
const underwater2: Array<Fish> = zoo.filter((p) => isFish(p))