Skip to content

Factory closure constructor inferring type act like "not sure" or "confused" #52245

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
renjithspace opened this issue Jan 15, 2023 · 3 comments
Closed
Labels
Duplicate An existing issue was already created

Comments

@renjithspace
Copy link

Bug Report

🔎 Search Terms

closure, infer

🕗 Version & Regression Information

  • I think this is a generic issue, not a specific version related

💻 Code

// Example 1

class Car {
  speed = 45;
}

/**
 * Vehicle factory constructor
 * 
 * This Vehicle constructor simply return
 * and instance of Car.
 */
class Vehicle {
  speed = 35;

  constructor() {
    return new Car();
  }
}

const vehicle = new Vehicle(); // 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 2

type VehicleType = "car" | "motorcycle";

class Car {
  speed = 35;
}

class Motorcycle {
  speed = 45;
}

class Vehicle {
  static construct(type: VehicleType) {
    switch (type) {
      case "car":
        return new Car();
      case "motorcycle":
        return new Motorcycle();
      default:
        throw new Error("Invalid vehicle type");
    }
  }
}

const vehicle = 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.

@IllusionMH
Copy link
Contributor

Looks related to or duplicate of #38519, #11588 etc.

@MartinJohns
Copy link
Contributor

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.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jan 23, 2023
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

5 participants