Imagine a scenario where a ChildClass is extending the ParentClass. You can view the code on Stackblitz here.
The ChildClass simply adds a public property called "brainPower":
class ParentClass{
_me: string;
constructor() {
this._me = "I'm a parent";
}
whoAmI(): string {
return this._me;
}
}
class ChildClass extends ParentClass {
public readonly brainPower = 42;
constructor() {
super();
this._me = "I'm a child";
}
}
In the code, there is a method named "doStuff" that takes a parameter which could be of either type:
class Program {
static main() {
Program.doStuff(new ParentClass());
Program.doStuff(new ChildClass());
}
static doStuff(anInstance: ParentClass | ChildClass){
console.log('[Program] > Processing > ', anInstance.whoAmI());
if(anInstance.brainPower){
console.log('[Processing] > ', anInstance.whoAmI(), ' > I can brain as much as ', anInstance.brainPower);
}
}
}
The issue arises when the Typescript compiler shows the error message:
Property 'brainPower' does not exist on type 'ParentClass | ChildClass'.
So the real Question here is how to define multiple possible types for a parameter and make sure that TypeScript can correctly understand it, allowing properties specific to one type only to be accepted?