To ensure accuracy, it is recommended to implement an interface (such as IPostUser
) on the Body
instead of creating a custom request object. Simply use the following code snippet:
interface IPostUser {
username: string
}
fastify.post('/:id', async (req: FastifyRequest<{ Params: { id: number }; Body: IPostUser }>, reply) => {
console.log(req.params.id)
console.log(req.body)
})
For an even more efficient solution, consider leveraging TypeScript's type refinement in conjunction with a Fastify JSON schema. Utilizing schemas is highly recommended!
In this scenario, employing Type Providers in Fastify, such as the package
@fastify/type-provider-json-schema-to-ts
, would be an optimal choice.