DEV Community

Cover image for TypeScript generics in routes — Fastify with TypeScript (part 6/18)
Antonio Tripodi
Antonio Tripodi

Posted on

TypeScript generics in routes — Fastify with TypeScript (part 6/18)

TypeScript generics in routes

Sixth chapter of the "Fastify with TypeScript" series. In the previous chapter we used as to tell TypeScript what request.body, request.params and request.query contain. In this one we replace those casts with Fastify's route generics, see what the compiler can now catch for us, and find out where generics stop helping.


The problem with as

This is the kind of line we wrote in chapter 5:

const { id } = request.params as { id: string };
Enter fullscreen mode Exit fullscreen mode

A cast is a promise you make to the compiler, and the compiler doesn't check it. Write as { userId: string } by mistake and it will happily let you read a property that will never exist. There is also one cast per handler, repeated every time you read the same data, and nothing at all describing what the route sends back.

Route generics

Every route method accepts a type parameter describing the route: Params, Querystring, Body, Headers and Reply. You declare the shape once, and request and reply are typed everywhere inside the handler.

Replace the content of src/users/users.route.ts with:

// src/users/users.route.ts
import type { FastifyInstance } from 'fastify';
import { createUserSchema } from './users.schema.ts';

interface User {
  id: string;
  name: string;
  email: string;
}

interface ListUsersRoute {
  Querystring: { limit?: string };
  Reply: User[];
}

interface GetUserRoute {
  Params: { id: string };
  Reply: {
    200: User;
    404: { error: string };
  };
}

interface CreateUserRoute {
  Body: { name: string; email: string };
  Reply: { 201: User };
}

export default async function userRoutes(fastify: FastifyInstance) {
  // Temporary in-memory storage: PostgreSQL replaces it in chapter 13
  const users: User[] = [];

  fastify.get<ListUsersRoute>('/', async (request) => {
    const { limit = '10' } = request.query; // string | undefined, no cast
    return users.slice(0, Number(limit));
  });

  fastify.get<GetUserRoute>('/:id', async (request, reply) => {
    const { id } = request.params; // string
    const user = users.find((u) => u.id === id);
    if (!user) {
      return reply.code(404).send({ error: 'User not found' });
    }
    return user;
  });

  fastify.post<CreateUserRoute>('/', { schema: createUserSchema }, async (request, reply) => {
    const { name, email } = request.body; // { name: string; email: string }
    const user: User = { id: crypto.randomUUID(), name, email };
    users.push(user);

    reply.code(201);
    reply.header('Location', `/api/v1/users/${user.id}`);
    return user;
  });
}
Enter fullscreen mode Exit fullscreen mode

The behavior is exactly the same as before, and the same curl commands from chapter 5 still work. What changed is that the three casts are gone, and each route now has a small interface that says what goes in and what comes out.

Reply can be written in two ways. Reply: User[] describes a single payload. Reply: { 200: User; 404: { error: string } } describes a different payload for each status code, which is what a real API needs: success and failure rarely look the same.

What the compiler catches now

Run npm run typecheck after each of these changes to see the generics at work. Undo each one before trying the next.

A typo in a parameter name. Change the first line of the GET /:id handler to const { userId: id } = request.params;:

error TS2339: Property 'userId' does not exist on type '{ id: string; }'.
Enter fullscreen mode Exit fullscreen mode

A status code the route doesn't declare. Change reply.code(404) to reply.code(500):

error TS2345: Argument of type '500' is not assignable to parameter of type '200 | 404'.
Enter fullscreen mode Exit fullscreen mode

The wrong payload for a status code. Change the 404 payload to { message: 'User not found' }:

error TS2353: Object literal may only specify known properties, and 'message' does not exist in type '{ error: string; }'.
Enter fullscreen mode Exit fullscreen mode

A response with a missing field. In the POST handler, replace return user; with return { id: user.id, name };:

Type '{ id: string; name: string; }' is not assignable to type 'void | User | { 201: User; }'.
Enter fullscreen mode Exit fullscreen mode

Every one of these would have gone unnoticed with the casts of chapter 5, and reached your users as a bug.

Typing an extracted handler

Handlers don't have to be inline. When you extract one into a named function (to reuse it across routes, or to unit-test it on its own), the same interface types its parameters through FastifyRequest and FastifyReply:

import type { FastifyRequest, FastifyReply } from 'fastify';

export async function createUser(
  request: FastifyRequest<CreateUserRoute>,
  reply: FastifyReply<CreateUserRoute>,
) {
  const { name, email } = request.body;
  reply.code(201);
  return { id: crypto.randomUUID(), name, email };
}

// in the plugin:
fastify.post<CreateUserRoute>('/', createUser);
Enter fullscreen mode Exit fullscreen mode

FastifyReply<RouteGeneric> with the route generic in first position is the Fastify 5 signature. In Fastify 4 the route generic came fourth, so if you find older snippets that look different, that's why.

The limit of generics

Generics describe what you expect to receive. They don't check what actually arrives. Try it: in ListUsersRoute, declare the limit as a number, and use it as one:

interface ListUsersRoute {
  Querystring: { limit?: number };
  Reply: User[];
}
Enter fullscreen mode Exit fullscreen mode
  fastify.get<ListUsersRoute>('/', async (request) => {
    const { limit = 10 } = request.query;
    console.log(typeof limit, limit + 1);
    return users.slice(0, limit);
  });
Enter fullscreen mode Exit fullscreen mode

npm run typecheck is happy: as far as TypeScript knows, limit is a number. Now call the route:

curl "localhost:3000/api/v1/users?limit=5"
Enter fullscreen mode Exit fullscreen mode

and look at the server's terminal:

string 51
Enter fullscreen mode Exit fullscreen mode

The value is still the string '5', exactly as chapter 5 warned, and limit + 1 glued the two together into '51' instead of adding them. The interface claimed number, nobody verified it, and the code is now wrong in a way the compiler can't see. Put the route back as it was before going on.

The POST route has the opposite problem. There the body is verified, by the JSON Schema we wrote in chapter 5, but the schema and the Body interface are two separate descriptions of the same thing, kept in sync by hand. Change one, forget the other, and they drift apart silently.

Both problems have the same solution: describe the data once, and get the runtime validation and the TypeScript types from that single description. That's what TypeBox and Fastify's type provider do, and with them you won't need to write these generics by hand anymore. That's the next chapter.


⬅️ Previous chapter: Routing and request handling · ➡️ Next chapter: Validation with schemas (TypeBox)

This article is part of the "Fastify with TypeScript" series — chapter 6 of 18.

Top comments (0)