While working with TypeScript, I encountered an issue when trying to implement the factory pattern. Specifically, I am unable to access child functions that do not exist in the super class without encountering a compiler error.
Here is the structure of my code:
abstract class Animal {
walk(meters:number) { ... }
}
class Elephant extends Animal {
walk(meters:number) { ... }
}
class Eagle extends Animal {
walk(meters:number) { ... }
fly(meters:number) { ... }
}
This is how my factory is set up:
class Zoo {
animals:Animal[] = [];
addAnimal(type:string): Animal {
var a: Animal;
switch(type) {
case 'elephant':
a = new Elephant();
break;
case 'eagle':
a = new Eagle();
break;
default:
throw new Error('Animal of type \'' + type + '\' doesn\t exist');
}
this.animals.push(a);
return a;
}
}
After creating an animal instance using the factory method, I attempted to call a function specific to the child class:
var sammy:Animal = addAnimal('eagle');
sammy.fly(15);
However, this resulted in the following error message: Error: TS2339: Property 'fly' does not exist on type 'Animal'.
I also tried to cast the variable to the child class explicitly:
var sammy:Eagle = addAnimal('eagle');
sammy.fly(15)
But this led to another error: Error: TS2322: Type 'Animal' is not assignable to type 'Eagle'. Property 'fly' is missing in type 'Animal'.
If you want to see and test the code yourself, I have created a playground on the TypeScript page: