title: Return the function input if it extends the generic type, otherwise null
body: <p>I am trying to type up a filter function which takes a generic parameter and enforces that the return type of the function given is either the input if it matches the generic or <code>null</code> if not.</p>
  <pre><code>type A = { type: 'A' };
  type B = { type: 'B' };
  
  type Union = A | B;
  const filter = &lt;T extends Union&gt;(filter: &lt;E extends Union&gt;(item: E) =&gt; E extends T ? E : null) =&gt; {
    // something
  };
  
  filter&lt;A&gt;((item) =&gt; { 
  // Argument of type '&lt;E extends Union&gt;(item: E) =&gt; E | null' is not assignable to parameter of type '&lt;E extends Union&gt;(item: E) =&gt; E extends A ? E : null'. 
  // Type 'E | null' is not assignable to type 'E extends A ? E : null'. 
  // Type 'null' is not assignable to type 'E extends A ? E : null'.(2345)
    if (item.type === 'A') return item;
  
    return null;
  });
  </code></pre>
  <p>I do not quite understand why this is not working. I suppose the error message is a bit misleading, I suspect TS does not understand that <code>if (item.type === 'A') return item;</code> actually satisfies the <code>E extends A ? E</code> part?</p>
  <p>I suppose I could also use a type guard, but this would not enforce that all types of <code>T</code> will be returned.</p>
  <p><a href="https://www.typescriptlang.org/play?#code/C4TwDgpgBAglC8UDeVSQFxQOQy1AvgNwCwAUGtAEILKrgSZaV5FlkVQCqAdgJYD23GnAA+USiVIBjQQGdgUAGa8ANsAgAnGgB4AKlAgAPddwAmsrn0EA+ABTK1mzNoCiB4xDMWeA7nd7qALaYLgCUCNZQbkYm5lD6APxRUJjcAK4qKuHwkUhkUFAA9IVQsvyBEMAAFrzcAOZkrKRszaQO6hraMHa2ARCB2bn5ULyKUL1BAHQc8LPYuOEalWkaQn2BksNLwCtC6ZmS+KGEQA" rel="nofollow noreferrer">Typescript playground</a></p>