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");