Alvin
Alvin

Reputation: 8499

fastify route request and response handler type in Typescript

Anyone know what is the request and response handler type in fastify?

Now I am just using 'any', typescript eslint gave me a warning:

fastify.post('/ac', async(req: any , res: any) => {

Upvotes: 7

Views: 7939

Answers (2)

Melroy van den Berg
Melroy van den Berg

Reputation: 3205

The correct answer should be to use an interface (eg. IPostUser) on Body, no need to create a whole custom request object, just do:

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)
})

Or even better, you do not want to refine the types again in TypeScript if you also created a Fastify JSON schema. Yes, you really should use schemas!

In that case, you can better use Type Providers in Fastify, like the package @fastify/type-provider-json-schema-to-ts.

Upvotes: 0

Arevi
Arevi

Reputation: 201

The appropriate types you're looking for are "FastifyRequest" and "FastifyReply", respectively.

They can be imported and implemented as shown below.

import { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';

fastify.post('/ac', async (req: FastifyRequest, res: FastifyReply) => {

});

Upvotes: 20

Related Questions