Let's say I have two different classes:
class Car{
drive(){
console.log('Driving!')
}
}
class Plane{
fly(){
console.log('Flying!')
}
}
And then there is a simple factory, that returns a different object, based on the string provided:
type PossibleObjects = 'car' | 'plane';
function vehicleFactory(wantedObject:PossibleObjects){
if(wantedObject === 'car')return new Car()
if(wantedObject === 'plane')return new Plane()
return new Car()//Just to avoid undefined
}
When I call this factory, Typescript doesn't seem to recognize the specific object that was returned:
const bmw = vehicleFactory('car')//Would expect Typescript to infer the resulted object from now on.
bmw.drive()//Error: Property 'drive' does not exist on type 'Car | Plane'. Property 'drive' does not exist on type 'Plane'.
Even though "vehicleFactory" is clearly called with "car" argument, Typescript doesn't recognize any method on "bmw", because Car and Plane do not share this method.
Is there any way to overcome this, and make TS aware of the specific object returned?
CodePudding user response:
You can check the type with instanceof
word:
const bmw = vehicleFactory('car') as Car;
if(bmw instanceof Car) {
bmw.drive();
} else if(bmw instanceof Plane) {
bmw.fly();
}
CodePudding user response:
Try explicitly casting the Type.
const bmw = vehicleFactory('car') as Car;