【发布时间】:2017-12-14 16:18:34
【问题描述】:
我有一些typescript接口、抽象类和实现子类:
// Animal classes
abstract class Animal {
abstract sound(): string;
constructor(public name: string) {
}
eat(food: string): string {
return "I eat this now: " + food;
}
}
class Snake extends Animal{
constructor() {
super("Snake");
}
sound() {
return "Sssssss";
}
}
class Owl extends Animal{
constructor() {
super("Owl");
}
sound() {
return "Hu-huu";
}
// Owl can also fly!
fly() {
return "I can flyyyy";
}
}
// Box classes
interface BoxInterface {
animal: Animal;
}
class Box implements BoxInterface {
animal: Animal;
constructor(animal: Animal) {
this.animal = animal;
}
}
如您所见,我们的想法是我们在框中有一个Box 和某种Animal - 在我们的示例中,它可以是Snake 或Owl。
现在我们可以在里面创建Box 和Owl。
let box = new Box( new Owl() );
现在的问题 - 使用在超类中声明的任何方法都完全没问题:
box.animal.sound(); // this is fine
但是正如你所看到的,Owl 有额外的功能 fly() 并且因为 fly 没有在 Animal 中声明它会抛出:
box.animal.fly(); // Property 'fly' does not exist on type 'Animal'.
创建普通变量时也会发生同样的情况:
let animal:Animal;
animal = new Owl();
animal.fly();
由于添加的Animal类不必是抽象的,它可以是普通类或接口-结果是一样的。
我的问题是:如果我的班级是其他班级的超集,为什么打字稿会抛出它。我认为接口和类型的主要思想是保证对象具有一些属性,如本例中的eat() 或sound()。
我在打字稿方面很新,所以可能是我错过了一些东西,无论如何我如何才能实现某些变量必须是某种类型但允许在子类中使用其他方法?
【问题讨论】:
标签: javascript typescript inheritance typescript2.0