Fastify typescript :未知体

eqoofvh9  于 2022-11-18  发布在  TypeScript
关注(0)|答案(2)|浏览(120)

这是我第一次使用Fastify,我在尝试访问Typescript正文中的值时遇到了问题。
有什么想法或建议吗?谢谢!

**更新:**我希望避免使用app.get(...)等来简化代码

这是我的代码:
App.ts

const buildServer = (options = {}) => {
  const app = fastify(options);
  app.register(routesApiV1, { prefix: '/api'});
  return app;
}

Routes.ts

const routesApiV1: FastifyPluginCallback = (fastify, options, done) => {
  fastify.route(userRoute);
  done();
}

User.ts

const handler: RouteHandlerMethod = async (req, res) => {
  const {
    name,
    lastName,
    dateOfBirth,
    addressLine,
    zipCode,
    city,
    country
  } = req.body; // Property '...' does not exist on type 'unknown'
  
  ...
}

const route: RouteOptions = {
  method: 'GET',
  url: '/user/:id',
  // schema: fastifySchema, Tried but not working
  handler,
  preValidation,
}
8yoxcaq7

8yoxcaq71#

您需要声明类型并键入RouteHandlerMethodRouteOptions,方法如下:
类型

type Body = {
  name: string;
  // ...
}

type Response = {
   // ...
}

路由处理程序方法

import { RawReplyDefaultExpression, RawRequestDefaultExpression, RawServerDefault, RouteHandler, RouteHandlerMethod } from "fastify";

const handler: RouteHandlerMethod<
    RawServerDefault,
    RawRequestDefaultExpression,
    RawReplyDefaultExpression,
    { Reply: Response; Body: Body }
>  = async (req, res) => {
  const {
    name,
    lastName,
    dateOfBirth,
    addressLine,
    zipCode,
    city,
    country
  } = req.body; // Property '...' does not exist on type 'unknown'
  
  ...
}

路线选项

import { RawReplyDefaultExpression, RawRequestDefaultExpression, RawServerDefault, RouteHandler, RouteHandlerMethod, RouteOptions } from "fastify";

const route: RouteOptions<RawServerDefault,
RawRequestDefaultExpression,
RawReplyDefaultExpression,
{ Reply: Response, Body: Body }> = {
  method: 'GET',
  url: '/user/:id',
  // schema: fastifySchema, Tried but not working
  handler,
  preValidation,
}
vi4fp9gy

vi4fp9gy2#

FastifyRequest类型是泛型类型。您应该将主体类型传递给它...

import type { FastifyRequest } from 'fastify'

interface BodyType {
  name: string
}

const handler = async (req: FastifyRequest<{ Body: BodyType }>) => {
    const { name } = req.body
}

当您使用RouteHandlerMethod时,它默认将request对象键入为FastifyRequest<{ Body: unknown }>,因此body的类型是未知的

相关问题