How to add TypeScript types to request body in Next.js API route?
julio's answer works but it is not encouraged by the official documentation :
Extending the req/res objects with TypeScript
const add = (a: number, b: number): number => a + b;
export default async (req: NextApiRequest, res: NextApiResponse) => {
const { body } = req;
try {
if (
"number_one" in body &&
typeof body.number_one === "number" &&
"number_two" in body &&
typeof body.number_two === "number"
) {
const result = add(body.number_one, body.number_two);
return res.status(200).json(result);
}
throw new Error("number_one or number_two is not a number");
} catch (err) {
return res.status(403).json({ err: "Error!" });
}
};
I haven't modified your code much so that you can integrate it easily, if you have the courage to come and modify this brick despite the fact that it "works"
You can create a new interface that extends NextApiRequest
and adds the typings for the two fields.
interface ExtendedNextApiRequest extends NextApiRequest {
body: {
number_one: number;
number_two: number;
};
}
Then use it to type the req
object in the handler function.
export default async (req: ExtendedNextApiRequest, res: NextApiResponse) => {
//...
};
While extending the NextApiRequest
type will stop TypeScript from complaining, it does not prevent potential runtime errors from occurring.
For a better, type-safe approach that narrows down the types instead, check out @Matthieu Gellé's answer.