title: 'R' could be instantiated with an arbitrary type which could be unrelated to 'Response<Command>'
body: <p>Ok, so I'm trying to implement a simple &quot;Command Bus&quot; in TypeScript, but I'm tripping up over generics and I wonder if someone could help me. Here is my code:</p>
  <p>This is the interface for the commandbus</p>
  <pre class="lang-js prettyprint-override"><code>export default interface CommandBus {
    execute: &lt;C extends Command, R extends Response&lt;C&gt;&gt;(command: C) =&gt; Promise&lt;R&gt;;
  }
  </code></pre>
  <p>This is the implementation</p>
  <pre class="lang-js prettyprint-override"><code>export default class AppCommandBus implements CommandBus {
    private readonly handlers: Handler&lt;Command, Response&lt;Command&gt;&gt;[];
  
    /* ... constructor ... */
  
    public async execute&lt;C extends Command, R extends Response&lt;C&gt;&gt;(
      command: C
    ): Promise&lt;R&gt; {
      const resolvedHandler = this.handlers.find(handler =&gt;
        handler.canHandle(command)
      );
  
      /* ... check if undef and throw ... */
  
      return resolvedHandler.handle(command);
    }
  }
  </code></pre>
  <p>and this is what the <code>Handler</code> interface looks like:</p>
  <pre class="lang-js prettyprint-override"><code>export default interface Handler&lt;C extends Command, R extends Response&lt;C&gt;&gt; {
    canHandle: (command: C) =&gt; boolean;
    handle: (command: C) =&gt; Promise&lt;R&gt;;
  }
  </code></pre>
  <p><code>Command</code> is (currently) an empty interface, and <code>Response</code> looks like this:</p>
  <pre><code>export default interface Response&lt;C extends Command&gt; {
    command: C;
  }
  </code></pre>
  <p>I'm getting the follow compile error error against the last line of the <code>execute</code> function of the commandbus and I'm completely stumped.</p>
  <p><code>type 'Response&lt;Command&gt;' is not assignable to type 'R'. 'R' could be instantiated with an arbitrary type which could be unrelated to 'Response&lt;Command&gt;'.</code></p>
  <p>If anyone is able to help me understand what I'm doing wrong, I'd be eternally grateful!</p>
  <p><strong>EDIT</strong></p>
  <p>I've realised I can work around this with a typecast:</p>
  <pre><code>const resolvedHandler = (this.handlers.find(handler =&gt;
    handler.canHandle(command)
  ) as unknown) as Handler&lt;C, R&gt; | undefined;
  </code></pre>
  <p>But I'd still like to know how to resolve this double cast.</p>