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