Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
Genérico debe ser una clase de salida en mecanografiado en el método de fábrica

Me gustaría pasar un genérico para poder escribir previamente mi clase devuelta.

 public createVehicle<O extends AbstractVehicle>( type: string ): O { switch (type) { case "Car": return new Car(param1, param2); case OfferType.Sale: return new Bike(param3, param4) default: throw new Error("Vehicle type not supported"); } }

sin embargo esto me da:

 Type 'Car' is not assignable to type 'O'. 'Car' is assignable to the constraint of type 'O', but 'O' could be instantiated with a different subtype of constraint 'AbstractVehicle'

lo cual entiendo, ya que puede ser algo como AbstractVehicle & {} , pero ¿no debería ser algo fácil de hacer?

Intenté durante horas sin solución, sigue arrojando ese error. ¿Alguna sugerencia para mantener esto simple y legible?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Su función no es genérica sobre su tipo de retorno. solo debes escribir

 createVehicle(type: string): Car | Bike

o

 createVehicle(type: string): AbstractVehicle

y llámelo como createVehicle("Car") as Car not createVehicle<Car>("Car") .

En todo caso, su función es genérica sobre su tipo de argumento, y puede inferir el tipo de retorno de eso:

 public createVehicle<T extends "Car" | "Bike">(type: T): T extends "Car" ? Car : T extends "Bike" ? Bike : never

Esto inferirá el tipo de resultado correcto para la llamada createVehicle("Car") (es decir typeof createVehicle<"Car">("Car") = Car ), pero para createVehicle(unknownType) seguirá infiriendo la unión.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!