簡體   English   中英

將超類或接口分配給子類

[英]Assign Superclass or Interface to Subclass

我有以下安裝程序:

class Dog extends Animal{}

class Animal{}

因此基本的繼承設置。 現在我有一個包含所有動物的類

class Farm{
     animals: Animal[];
}

現在,在應用程序中的某個時刻,我需要遍歷數組,一旦找到了Dog,我就想將其分配給變量:

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

但這給了我兩個錯誤。 首先,instanceof不起作用,它說參數的右手為空。

第二個錯誤是,動物類型不能分配給狗類型。 當我將Animal聲明為Interface時,也會發生同樣的情況。

instanceof錯誤必須是一些錯字,那里的instanceof很好。

您不能分配this.dog = animal;的原因this.dog = animal; 是您需要強制轉換(不過,奇怪的是,我無法讓TypeScript游樂場向我展示該錯誤):

this.dog = <Dog>animal;

要么

this.dog = animal as Dog;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM