Menu

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

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

DEV Community: fastify·Antonio Tripodi·11 days ago
#UV8cyGCe
#devtofastify#devto#dev#user#string
Long article (1364 words) — no AI summary yet.
Reading 0:00
15s threshold

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 .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.