title: TypeScript: How to type object rest spread for any keys in function
body: <p>I have a function that takes an object and returns an object. It returns the whole incoming object, but adds a key. The shape of the object is unknown, so it could have any keys, but it must have 2 certain keys.</p>
  <pre><code>const myFunction = ({
    num1,
    num2,
    ...rest
  }: {
    num1: number;
    num2: number;
  }) =&gt; ({
    num1,
    num2,
    sum: num1 + num2,
    ...rest,
  });
  
  myFunction({ num1: 4, num2: 3, foo: 'bar' });
  // or myFunction({ num1: 4, num2: 3, baz: 'qux', quux: 'quuz' });
  </code></pre>
  <p>Here TypeScript yells about <code>foo</code>.</p>
  <pre><code>Argument of type '{ num1: number; num2: number; foo: string; }' is not assignable to parameter of type '{ num1: number; num2: number; }'.
    Object literal may only specify known properties, and 'foo' does not exist in type '{ num1: number; num2: number; }
  </code></pre>
  <p>That was the simplified example.</p>
  <p>Here is my actual function and how I tried to solve it using <code>extends</code>.</p>
  <pre><code>import type { NextApiRequest, NextApiResponse } from 'next';
  import { getSession } from 'utils/sessions';
  
  const withAuthentication = async &lt;
    T extends {
      request: NextApiRequest;
      response: NextApiResponse;
    },
    K extends T
  &gt;({
    request,
    response,
    ...rest
  }: T): Promise&lt;
    {
      userSession: {
        issuer: string;
        publicAddress: string;
        email: string;
      };
    } &amp; K
  &gt; =&gt; {
    const userSession = await getSession(request);
  
    return { request, response, userSession, ...rest };
  };
  
  export default withAuthentication;
  </code></pre>
  <p>And the actual error is this.</p>
  <pre><code>Type '{ request: NextApiRequest; response: NextApiResponse&lt;any&gt;; userSession: any; } &amp; Omit&lt;T, &quot;request&quot; | &quot;response&quot;&gt;' is not assignable to type '{ userSession: { issuer: string; publicAddress: string; email: string; }; } &amp; K'.
    Type '{ request: NextApiRequest; response: NextApiResponse&lt;any&gt;; userSession: any; } &amp; Omit&lt;T, &quot;request&quot; | &quot;response&quot;&gt;' is not assignable to type 'K'.
      '{ request: NextApiRequest; response: NextApiResponse&lt;any&gt;; userSession: any; } &amp; Omit&lt;T, &quot;request&quot; | &quot;response&quot;&gt;' is assignable to the constraint of type 'K', but 'K' could be instantiated with a different subtype of constraint '{ request: NextApiRequest; response: NextApiResponse&lt;any&gt;; }'.
  </code></pre>
  <p>How can you type such a function?</p>