Reputation: 6406
Consider a ChildClass extending the ParentClass. Stackblitz available here for this question.
ChildClass only adds a public property ("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";
}
}
A method "doStuff" takes one parameter of either kinds:
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);
}
}
}
My problem
The Typescript compiler reports:
Property 'brainPower' does not exist on type 'ParentClass | ChildClass'.
Question is how to set multiple possible types for a parameter and expect typescript to understand it so that a property only known to one of the types is accepted?
Upvotes: 0
Views: 351
Reputation: 3199
You can set the parameter of the function to accept any instance of ParentClass
.
Instead of checking if the property exists, you could check if the given object is an instance of ChildClass
if (anInstance instanceof ChildClass) ...
The ts compiler will infer the object as an instance of ChildClass within the if scope.
Upvotes: 2