Fastify Typescript request query

Viewed 6961

I'm trying to put together a simple endpoint following the Fastify with Typescript docs here:

https://www.fastify.io/docs/v3.1.x/TypeScript/

export default async function foo(fastify: any) {
       const MyInstance = new Foo(fastify.db);
       app.get<{ Querystring: IQueryString, Headers: IHeaders }>(
           "/foo",
           async (request: FastifyRequest, reply: FastifyReply) => {
              console.log(request.query); // *prints query object*
              const { queryObj } = request.query; // *Gives error: Object is of type 'unknown'*
              const result = await MyInstance.getFoo(queryObj);
              reply.status(200).send(result);
           }
       );
   }

Why do I get the error when I try to access the request.query object and how do I fix it?

2 Answers

By default FastifyRequest.query's type RequestQuerystringDefault maps to unknown because one cannot guess which attributes/type you'll want to set for it.

Should you have a defined type for the query of some request, just define that request type and use it:

type MyRequest = FastifyRequest<{
  Querystring: { queryObj: MyQueryObject }
}>

then specify it as the expected request type:

 async (request: MyRequest, reply: FastifyReply) => {
   const { queryObj } = request.query // Ok
 }

If you write the code to look it like Express.js, try that one:

app.get('/foo', async (req: FastifyRequest<{
            Params: {
              name: string,
            };
        }>,
        rep: FastifyReply,) => {
  const name = req.params.name // string
})

Related