title: How to write a TypeScript type utility that narrows union types in an object?
body: <p>I've got a bunch of generated types (via GraphQL codegen) that look like this:</p>
  <pre><code>type X = {
    a?: Maybe&lt;number&gt;
    b?: Maybe&lt;Array&lt;MyType&gt; | MyType&gt;
    c?: Maybe&lt;MyType2&gt;
    d?: Maybe&lt;Array&lt;MyType3&gt; | MyType3&gt;
  }
  
  // Maybe is:
  // type Maybe&lt;T&gt; = T | null | undefined;
  </code></pre>
  <p>For fields <code>b</code> and <code>d</code>, the codegen does the right thing according to GraphQL spec (see <a href="https://github.com/dotansimha/graphql-code-generator/issues/4888" rel="nofollow noreferrer">this issue</a>) but in my specific codebase, I need to transform all the types to basically this:</p>
  <pre><code>type X2 = {
    a?: Maybe&lt;number&gt;
    b?: Maybe&lt;Array&lt;MyType&gt;&gt;
    c?: Maybe&lt;MyType2&gt;
    d?: Maybe&lt;Array&lt;MyType3&gt;&gt;
  }
  </code></pre>
  <p>How to write a <strong>type utility</strong> that does this?</p>
  <p>(Manually, it would be done like this:)</p>
  <pre><code>type X2 = Omit&lt;X, 'b' | 'd'&gt; &amp; {
    b?: Maybe&lt;Array&lt;MyType&gt;&gt;;
    d?: Maybe&lt;Array&lt;MyType3&gt;&gt;;
  };
  </code></pre>