8

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) => { 
3
  • What version are you using? Commented Sep 6, 2020 at 20:32
  • I am using version 3. Commented Sep 9, 2020 at 8:30
  • @Alvin can you try with tslint instead of eslint Commented May 29, 2021 at 11:55

2 Answers 2

21

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) => { }); 
Sign up to request clarification or add additional context in comments.

5 Comments

When I try to access req.body.object, it prompted err at object - Property 'object' does not exist on type 'unknown'.ts(2339)
fastify.io/docs/latest/TypeScript/#request is helpful (the type CustomRequest = FastifyRequest<{ Body: .. }> part) for getting the req body typed
why was this so hard to find??
It's still the wrong answer, see my answer below.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.