title: TypeScript: Factory function for union types
body: <p>I have a custom <code>Factory</code> type that lets me create factory functions.</p>
  <pre><code>export type Factory&lt;T&gt; = (state?: Partial&lt;T&gt;) =&gt; T;
  </code></pre>
  <p>I have an <code>&lt;Avatar /&gt;</code> React component that has a union type as prop because there can be two versions of it (just the image, or clickable image). In other words, the component can have either or props.</p>
  <pre><code>type AvatarOnlyProps = {
    alt: string;
    src: string;
  };
  
  type ClickableAvatarProps = {
    alt: string;
    label: string;
    onClick:
      | ((event: React.MouseEvent&lt;HTMLButtonElement, MouseEvent&gt;) =&gt; void)
      | undefined;
    src: string;
  };
  
  export type AvatarProps = AvatarOnlyProps | ClickableAvatarProps;
  </code></pre>
  <p>I want to create a factory function for the avatar's props. I tried typing it like this:</p>
  <pre><code>const createProps: Factory&lt;AvatarProps&gt; = ({
    alt = 'Your avatar',
    label,
    onClick,
    src: source = '/images/default-avatar.png',
  } = {}) =&gt; ({ alt, label, onClick, src: source });
  </code></pre>
  <p>But TypeScript complains:</p>
  <pre><code>Property 'label' does not exist on type 'Partial&lt;AvatarOnlyProps&gt; | Partial&lt;ClickableAvatarProps&gt;'.
  </code></pre>
  <p>in the arguments of the factory function.</p>
  <p><a href="https://i.stack.imgur.com/xvf1v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xvf1v.png" alt="enter image description here" /></a></p>
  <p>How can I make the error go away? How can I get TypeScript to under stand, that in this factory function either both <code>onClick</code> and <code>label</code> will be supplied, or neither?</p>