You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I think this is a generic issue, not a specific version related
💻 Code
// Example 1classCar{speed=45;}/** * Vehicle factory constructor * * This Vehicle constructor simply return * and instance of Car. */classVehicle{speed=35;constructor(){returnnewCar();}}constvehicle=newVehicle();// Inferring as instance of `Vehicle` instead of `Car`, why?console.log(vehicle.speed);// 45// If `vehicle` is an instance of `Vehicle` the `vehicle.speed` should return 35, right?
// Example 2typeVehicleType="car"|"motorcycle";classCar{speed=35;}classMotorcycle{speed=45;}classVehicle{staticconstruct(type: VehicleType){switch(type){case"car":
returnnewCar();case"motorcycle":
returnnewMotorcycle();default:
thrownewError("Invalid vehicle type");}}}constvehicle=Vehicle.construct("car");//Inferring as `Car` | `Motorcycle`, why not just `Car`?console.log(vehicle.speed);// 35// There's no confusion for runtime,// it clearly identifies vehicle is a car and returns its `speed` correctly// Is this a weakness of inferring types in typescript?
🙁 Actual behavior
In both examples, the Vehicle instance is not inferring the correct type that matches the runtime behavior.
🙂 Expected behavior
In both examples, the Vehicle instance infers the correct type that matches the runtime behavior.
The text was updated successfully, but these errors were encountered:
And regarding example 2: Nothing in the functions type signature it indicates that the argument "car" will always return a Car. TypeScript does not go and analyze the logic within the function to determine the return type.
Bug Report
🔎 Search Terms
closure, infer
🕗 Version & Regression Information
💻 Code
🙁 Actual behavior
In both examples, the
Vehicle
instance is not inferring the correct type that matches theruntime
behavior.🙂 Expected behavior
In both examples, the
Vehicle
instance infers the correct type that matches theruntime
behavior.The text was updated successfully, but these errors were encountered: