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

334
Views
Se podría crear una instancia de 'R' con un tipo arbitrario que podría no estar relacionado con 'Respuesta<Comando>'

Ok, entonces estoy tratando de implementar un "Bus de comando" simple en TypeScript, pero me estoy tropezando con los genéricos y me pregunto si alguien podría ayudarme. Aquí está mi código:

Esta es la interfaz para el bus de comandos.

 export default interface CommandBus { execute: <C extends Command, R extends Response<C>>(command: C) => Promise<R>; }

Esta es la implementación

 export default class AppCommandBus implements CommandBus { private readonly handlers: Handler<Command, Response<Command>>[]; /* ... constructor ... */ public async execute<C extends Command, R extends Response<C>>( command: C ): Promise<R> { const resolvedHandler = this.handlers.find(handler => handler.canHandle(command) ); /* ... check if undef and throw ... */ return resolvedHandler.handle(command); } }

y así es como se ve la Handler del controlador:

 export default interface Handler<C extends Command, R extends Response<C>> { canHandle: (command: C) => boolean; handle: (command: C) => Promise<R>; }

Command es (actualmente) una interfaz vacía, y Response se ve así:

 export default interface Response<C extends Command> { command: C; }

Recibo el siguiente error de compilación en la última línea de la función de execute del bus de comandos y estoy completamente perplejo.

type 'Response<Command>' is not assignable to type 'R'. 'R' could be instantiated with an arbitrary type which could be unrelated to 'Response<Command>'.

Si alguien puede ayudarme a entender lo que estoy haciendo mal, ¡estaría eternamente agradecido!

EDITAR

Me di cuenta de que puedo solucionar esto con un encasillado:

 const resolvedHandler = (this.handlers.find(handler => handler.canHandle(command) ) as unknown) as Handler<C, R> | undefined;

Pero aún me gustaría saber cómo resolver este doble elenco.

over 4 years ago · Santiago Trujillo
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!