10

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?

Aakshaye
  • 359
  • 1
  • 3
  • 17
  • 2
    Never annotate the types of inline callback parameters. Instead, use type inference. That is `async (request, reply) =>` instead of `async (request: FastifyRequest, reply: FastifyReply) =>`. Note: the examples in the docs you linked do this properly – Aluan Haddad Apr 27 '21 at 18:57
  • 1
    That fixes the error. However, type inference doesn't seem to work on ```async(request, reply) ```. I get no implicit any on ```request``` and ```reply```. – Aakshaye Apr 27 '21 at 19:53
  • 3
    @AluanHaddad Never say never. – n8jadams May 05 '21 at 20:24

2 Answers2

21

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
 }
Jérôme Beau
  • 10,608
  • 5
  • 48
  • 52
  • 1
    Link in the post is 404. Use [this one](https://www.fastify.io/docs/latest/Reference/TypeScript/#using-generics) instead. – Sumit Wadhwa Dec 28 '22 at 11:27
-5

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
})
kazington
  • 58
  • 5