15

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?

3
  • 3
    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 Commented Apr 27, 2021 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. Commented Apr 27, 2021 at 19:53
  • 4
    @AluanHaddad Never say never. Commented May 5, 2021 at 20:24

1 Answer 1

34

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

1 Comment

Link in the post is 404. Use this one instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.