title: TypeScript union function types
body: <p>I'm trying to create a union type for arrow functions. The goal would be to be able to infer the type of the second argument based on the first.</p>
  
  <p>Ideally I would like <code>y</code> to be of type <code>number | string</code>, and <code>z</code> to be <code>'first' | 'second'</code>. But after narrowing down the type of either <code>y</code> or <code>z</code>, infer the narrowed type of the other parameter automatically.</p>
  
  <p>Unfortunately TypeScript doesn't seem to handle a complex case like this, but I was wondering if any of you had ever faced a similar issue.</p>
  
  <p>In a simplified scenario my code looks like:</p>
  
  <pre><code>type Callback&lt;T1, T2&gt; = (y: T1, z: T2) =&gt; void;
  
  const test = (x: Callback&lt;number, 'first'&gt; | Callback&lt;string, 'second'&gt;) =&gt; {
      return;
  }
  
  // Parameter 'y' implicitly has an 'any' type.
  // Parameter 'z' implicitly has an 'any' type.
  test((y, z) =&gt; {
      if(typeof y === 'number') {
          // y is a number
          // so z must be 'first'
      } else {
          // y is a string
          // so z must be 'second'
      }
  });
  </code></pre>
  
  <p>Thanks!</p>