I’m struggling to understand the difference between these two concepts as they seem to just be 2 different ways to do the same thing.
Below is a code snippet from the fastify docs typescript section. It shows the schema which allows you to define, for example, the expected request body and the response for the route. In this case, you are expecting the body to contain the properties of a User and the response to be also a user. Great, that makes sense to me and if I were using javascript, then I would do that.
But when using typescript, you can also use generics to type the Body and Reply in the post function, which similarly specifies that the request expects a UserType in the body and will respond with a UserType.
How is this different than the schema? It seems these are alternative methods for the same thing, but this code example uses both so I think they must be serving different purposes.
https://fastify.dev/docs/latest/Reference/TypeScript/#typescript
import { Static, Type } from '@sinclair/typebox'
export const User = Type.Object({
name: Type.String(),
mail: Type.Optional(Type.String({ format: 'email' })),
})
export type UserType = Static<typeof User>
import Fastify from 'fastify'
import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox'
// ...
const fastify = Fastify().withTypeProvider<TypeBoxTypeProvider>()
fastify.post<{ Body: UserType, Reply: UserType }>(
'/',
{
schema: {
body: User,
response: {
200: User
},
},
},
(request, reply) => {
// The `name` and `mail` types are automatically inferred
const { name, mail } = request.body;
reply.status(200).send({ name, mail });
}
)