Typescript子类类型(Type Assertions)

Typescript subclass type (Type Assertions)

希望你喜欢动物。这是一个口语示例:

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

错误:类型 'Animal' 不可分配给类型 'Cat'。 属性 'Miaou' 在类型 'Animal' 中缺失。

有人能给我解释一下区别吗?我以为有 none...

编辑: 好的,打字稿规范中有详细说明:Type Assertions

class Shape { ... }
class Circle extends Shape { ... }
function createShape(kind: string): Shape {
 if (kind === "circle") return new Circle();
 ...
}
var circle = <Circle> createShape("circle");

"retrieveAnimal"函数return一个"Animal"类型的对象,但是这里

let retrievedCat: Cat = kennel.retrieveAnimal('Hubert');

你声明了 "retrievedCat" 类型的 "Cat" 变量,所以你确实不能将 Animal 转换为 Cat。

第二种情况:

let retrievedCat = <Cat> kennel.retrieveAnimal('Hubert');

你声明 "retrievedCat" 类型的 "any" 变量(你没有指定任何类型,所以默认 - "any"),并将值指定为 "Cat" .显然,您可以将 "Cat" 转换为 "any",恕我直言。