Typescript子类类型(Type Assertions)

时间:2015-10-17 18:06:06

标签: class inheritance types typescript subclass

我希望你喜欢动物。这是一个发言的例子:

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”属性。

有人能解释我的区别吗?我以为没有......

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

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

1 个答案:

答案 0 :(得分:0)

&#34; retrieveAnimal&#34;函数返回&#34; Animal&#34;的对象类型,但这里

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

你声明&#34; retrieveCat&#34; &#34; Cat&#34;的变量类型,所以你确实无法将Animal转换为Cat。

在第二种情况下:

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

你声明&#34; retrieveCat&#34; &#34;任何&#34;的变量类型(您没有指定任何类型,因此默认情况下 - &#34;任何&#34;),并指定值为&#34; Cat&#34;。显然,你可以施展&#34; Cat&#34;到&#34;任何&#34;,恕我直言。