2

This is my first time using Fastify and I'm facing an issue trying to access to the values in the body in Typescript.

Any idea or suggestion? Thanks!

Update: I would like to avoid to use app.get(...) etc to simplify the code

This is my code:

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,
}
  • Maybe Question [63753396](https://stackoverflow.com/questions/63753396/fastify-route-request-and-response-handler-type-in-typescript) would help? – Unili Sep 11 '22 at 01:09

2 Answers2

3

The FastifyRequest type is a generic type. You should pass it your body type...

import type { FastifyRequest } from 'fastify'

interface BodyType {
  name: string
}

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

When you use RouteHandlerMethod, it defaults to typing the request object as FastifyRequest<{ Body: unknown }>, hence the type of body being unknown

Charlie Martin
  • 8,208
  • 3
  • 35
  • 41
0

You need to declare the types and type the RouteHandlerMethod and RouteOptions, this way :

The types

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

type Response = {
   // ...
}

RouteHandlerMethod

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'
  
  ...
}

RouteOptions

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,
}
Julien TASSIN
  • 5,004
  • 1
  • 25
  • 40