Aakshaye
Aakshaye

Reputation: 399

Fastify Typescript request query

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?

Upvotes: 14

Views: 24279

Answers (1)

J&#233;r&#244;me Beau
J&#233;r&#244;me Beau

Reputation: 11450

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
 }

Upvotes: 32

Related Questions