希望你喜欢动物。下面是一个具体的例子:
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错误:不能将“动物”类型指定为键入“猫”。属性“Miaou”在“动物”类型中缺失。
有人能解释我的区别吗?我以为没有..。
编辑:确定,它在打字稿规范:类型断言中有详细说明。
class Shape { ... }
class Circle extends Shape { ... }
function createShape(kind: string): Shape {
if (kind === "circle") return new Circle();
...
}
var circle = <Circle> createShape("circle");
发布于 2015-10-17 18:26:21
"retrieveAnimal“函数返回一个”动物“类型的对象,但在这里
let retrievedCat: Cat = kennel.retrieveAnimal('Hubert');您声明"retrievedCat“变量的”猫“类型,所以您确实不能把动物给猫。
在第二种情况下:
let retrievedCat = <Cat> kennel.retrieveAnimal('Hubert');您可以声明" any“类型的"retrievedCat”变量(您没有指定任何类型,因此默认情况下为- "any"),并将值指定为"Cat“。显然,你可以把“猫”转换成“任何”,IMHO。
https://stackoverflow.com/questions/33189886
复制相似问题