There is a function that takes an object as input and returns an object as output. This function adds a key to the incoming object and returns the modified object. The object's structure is not known beforehand, but it must contain two specific keys.
const myFunction = ({
num1,
num2,
...rest
}: {
num1: number;
num2: number;
}) => ({
num1,
num2,
sum: num1 + num2,
...rest,
});
myFunction({ num1: 4, num2: 3, foo: 'bar' });
// or myFunction({ num1: 4, num2: 3, baz: 'qux', quux: 'quuz' });
In TypeScript, an error is reported for the 'foo' key.
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; }
The above was a simplified example. Now, let's look at a more complex function and an attempt to handle it using 'extends'.
import type { NextApiRequest, NextApiResponse } from 'next';
import { getSession } from 'utils/sessions';
const withAuthentication = async <
T extends {
request: NextApiRequest;
response: NextApiResponse;
},
K extends T
>({
request,
response,
...rest
}: T): Promise<
{
userSession: {
issuer: string;
publicAddress: string;
email: string;
};
} & K
> => {
const userSession = await getSession(request);
return { request, response, userSession, ...rest };
};
export default withAuthentication;
The actual error message for this function is as follows.
Type '{ request: NextApiRequest; response: NextApiResponse<any>; userSession: any; } & Omit<T, "request" | "response">' is not assignable to type '{ userSession: { issuer: string; publicAddress: string; email: string; }; } & K'.
Type '{ request: NextApiRequest; response: NextApiResponse<any>; userSession: any; } & Omit<T, "request" | "response">' is not assignable to type 'K'.
'{ request: NextApiRequest; response: NextApiResponse<any>; userSession: any; } & Omit<T, "request" | "response">' is assignable to the constraint of type 'K', but 'K' could be instantiated with a different subtype of constraint '{ request: NextApiRequest; response: NextApiResponse<any>; }'.
How would you define the type for such a function?