Ok, so I'm trying to implement a simple "Command Bus" in TypeScript, but I'm tripping up over generics and I wonder if someone could help me. Here is my code:
This is the interface for the commandbus
export default interface CommandBus {
execute: <C extends Command, R extends Response<C>>(command: C) => Promise<R>;
}
This is the implementation
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);
}
}
and this is what the Handler interface looks like:
export default interface Handler<C extends Command, R extends Response<C>> {
canHandle: (command: C) => boolean;
handle: (command: C) => Promise<R>;
}
Command is (currently) an empty interface, and Response looks like this:
export default interface Response<C extends Command> {
command: C;
}
I'm getting the follow compile error error against the last line of the execute function of the commandbus and I'm completely stumped.
type 'Response<Command>' is not assignable to type 'R'. 'R' could be instantiated with an arbitrary type which could be unrelated to 'Response<Command>'.
If anyone is able to help me understand what I'm doing wrong, I'd be eternally grateful!
EDIT
I've realised I can work around this with a typecast:
const resolvedHandler = (this.handlers.find(handler =>
handler.canHandle(command)
) as unknown) as Handler<C, R> | undefined;
But I'd still like to know how to resolve this double cast.