[英]Typescript subclass type (Type Assertions)
I hope you like animals. 我希望你喜欢动物。 Here is a speaking example :
这是一个说话的例子:
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
The error : Type 'Animal' is not assignable to type 'Cat'. 错误:“动物”类型不能分配给“猫”类型。 Property 'Miaou' is missing in type 'Animal'.
“动物”类型中缺少属性“ Miaou”。
Somebody can explain me the difference ? 有人可以解释我的区别吗? I thought there were none...
我以为没有...
EDIT : OK, It is detailed in the typescript specification : Type Assertions 编辑:好的,在打字稿规范中有详细说明: 类型断言
class Shape { ... } class Circle extends Shape { ... } function createShape(kind: string): Shape { if (kind === "circle") return new Circle(); ... } var circle = <Circle> createShape("circle");
The "retrieveAnimal" function return an object of the "Animal" type, but here “ retrieveAnimal”函数返回“ Animal”类型的对象,但是这里
let retrievedCat: Cat = kennel.retrieveAnimal('Hubert');
you declare "retrievedCat" variable of the "Cat" type, so you indeed can not cast Animal to Cat. 您声明了“ Cat”类型的“ retrievedCat”变量,因此您确实无法将Animal转换为Cat。
In the second case: 在第二种情况下:
let retrievedCat = <Cat> kennel.retrieveAnimal('Hubert');
you declare "retrievedCat" variable of the "any" type (you doesn't specify any type, so by default - "any"), and specify value as "Cat". 您声明“ any”类型的“ retrievedCat”变量(您未指定任何类型,因此默认情况下为“ any”),并将值指定为“ Cat”。 Obviously, you can cast "Cat" to "any", IMHO.
显然,恕我直言,您可以将“猫”转换为“任何”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.