Are you trying to figure out how to correctly define the body type of an API POST route in Next.js for better type safety?
In NextApiRequest, the body is currently defined as "any" and NextApiRequest itself is not generic.
I have tried forcefully assigning a type, but that solution feels messy.
Currently using Next.js 12 and TypeScript 4.4.4
import { NextApiRequest, NextApiResponse } from "next";
interface IBody {
test: string;
value: number;
}
const handler = async (
req: NextApiRequest, //<-- wish we could specify something here like NextApiRequest<TQuery, TBody,..>
res: NextApiResponse
): Promise<void> => {
const { body } = req;
console.log(body as IBody); //<-- this doesn't feel safe
res.status(200).json({ text: "Hello" });
};
export default handler;