如何在Typescript中找到函数参数实例的子类?

时间:2019-06-05 20:27:38

标签: typescript

我有三个班级:动物,猫和狗。猫和狗都延伸动物。我有一组动物对象。这些对象可以是猫或狗。

最初,我有两个功能,每个Animal子类一个。但是,由于它们本质上是做相同的事情(减去几行代码),所以我正在考虑将这两个函数组合在一起,然后将Animal数组作为参数传递,这实际上是Cat数组或Dog数组。为了实现每个类必须执行的几行不同的代码行,我需要获取数组中每个对象的类,但是我编写的代码无法弄清楚该对象是Cat类还是狗班。

我尝试过的代码如下。我也尝试过制造任何类型的动物,但都无济于事。

export class Animal{}

export class Cat extends Animal{}

export class Dog extends Animal{}

export class Service {

    public insert(animals: Animal[], callback: Function) {
        animals.forEach((c: Animal) => {
            if (c instanceof Cat) {
                var thisCat: Cat = <Cat>c;
                //...
            } else if (c instanceof Dog) {
                var thisDog: Dog = <Dog>c;
                //...
            }
        });
    }
}

这只能用一个功能完成吗?还是我必须为每个Animal子类保留两个单独的“服务”功能?

1 个答案:

答案 0 :(得分:0)

这在Typescript since 1.4中可以正常工作,甚至比您更容易:您不需要强制转换<Cat>c<Dog>c,因为instanceof是一种类型警卫队。

也就是说,您可以选择创建一个抽象函数(如注释中的Li357所述),以更好地组织代码,具体取决于您是希望动物还是服务部门承担适应新动物或新行为的责任。现有的动物。

Live link

class Animal{}

class Cat extends Animal{
    meow() {/* ... */}
}

class Dog extends Animal{
    bark() {/* ... */}
}

class Service {

    public insert(animals: Animal[], callback: Function) {
        animals.forEach((c: Animal) => {
            if (c instanceof Cat) {
                console.log("Inserted a cat: %s", c)
                c.meow();
            } else if (c instanceof Dog) {
                console.log("Inserted a dog: %s", c)
                c.bark();
            }
        });
    }
}

let s = new Service();
let animalArray = [new Cat(), new Dog(), new Cat()];
s.insert(animalArray, () => {});