【发布时间】:2016-01-16 08:27:06
【问题描述】:
我希望你喜欢动物。这是一个口语例子:
class Animal {
constructor(public name: string, public age: number) {}
}
class Cat extends Animal {
constructor(name: string, age: number) {
super(name, age);
}
public miaou() {
console.log('Miaou');
}
}
class Kennel {
animals = Map<string, Animal> new Map();
public addAnimal(animal: Animal): void {
this.animals.set(animal.name, animal);
}
public retrieveAnimal(name: string): Animal {
return this.animals.get(name);
}
}
let kennel = <Kennel> new Kennel();
let hubert = <Cat> new Cat('Hubert', 4);
kennel.addAnimal(hubert);
let retrievedCat: Cat = kennel.retrieveAnimal('Hubert'); // error
let retrievedCat = <Cat> kennel.retrieveAnimal('Hubert'); // Works
错误:“动物”类型不可分配给“猫”类型。 “动物”类型中缺少属性“妙欧”。
有人可以解释一下区别吗?我以为没有...
编辑: 好的,在打字稿规范中有详细说明:Type Assertions
class Shape { ... }
class Circle extends Shape { ... }
function createShape(kind: string): Shape {
if (kind === "circle") return new Circle();
...
}
var circle = <Circle> createShape("circle");
【问题讨论】:
标签: class inheritance types typescript subclass