0

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'.

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");
Tiramitsu
  • 61
  • 10

1 Answers1

0

The "retrieveAnimal" function return an object of the "Animal" type, but here

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

you declare "retrievedCat" variable of the "Cat" type, so you indeed can not cast Animal to 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". Obviously, you can cast "Cat" to "any", IMHO.

TSV
  • 7,538
  • 1
  • 29
  • 37
  • ok ! But how use those different kind of declaration ? Why not use only the seconde declaration ? Therefore, we could use retrievedAnimal = ... Thanks ! – Tiramitsu Oct 17 '15 at 18:43
  • It depends. If you are absolutely shure in the object's type, you can cast through the "any" type (variant 2). If not, you can check type with "instanceof" operator (http://stackoverflow.com/questions/12789231/class-type-check-with-typescript). – TSV Oct 17 '15 at 18:48