jeudi 23 novembre 2017

Assign Superclass or Interface to Subclass

I have following Setup:

class Dog extends Animal{}

class Animal{}

So basic Inheritance setup. Now I have a different class containing all Animals

class Farm{
     animals: Animal[];
}

Now at one point in the Application I need to iterate over the array, and once I find a Dog I want to assign it to a variable:

_.forEach(farm.animals, (animal:Animal)=>{
    if(animal instanceof Dog){
        this.dog = animal;
    }
}

But this gives me two errors. First the instanceof doesn't work, it says right handed side of argument is null.

And the second error is, that type Animal is not assignable to type Dog. The same happens, when I declare Animal as an Interface.




Aucun commentaire:

Enregistrer un commentaire