NodeJS Fastify Typescript请求查询

6jygbczu  于 2022-12-29  发布在  Node.js
关注(0)|答案(2)|浏览(153)

我尝试在Fastify with Typescript文档之后整理一个简单的端点:
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);
           }
       );
   }

为什么在我尝试访问request.query对象时会出现错误?如何修复它?

eqqqjvef

eqqqjvef1#

默认情况下,FastifyRequest.query的类型RequestQuerystringDefaultMap到unknown,因为人们无法猜测您将为其设置哪些属性/类型。
如果您已经为某个请求的query定义了一个类型,那么只需定义该请求类型并使用它:

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

然后将其指定为预期的请求类型:

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

g9icjywg2#

如果您编写的代码看起来像Express.js,请尝试以下代码:

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

相关问题