Using:
Fastify 5.1.0
Typescript 5.7.2
node 22.10.2 (target es2017)
I’m going through the Fastify 5.1.X Typescript generics tutorial from the Fastify web site (here: https://fastify.dev/docs/latest/Reference/TypeScript/) and I’m getting an error when I try to build:
Type 'Promise<string>' is not assignable to type 'void | IReply | Promise<void | IReply>'.
Type 'Promise<string>' is not assignable to type 'Promise<void | IReply>'.
Type 'string' is not assignable to type 'void | IReply'.
33 }, async (request, reply) => {
~~~~~~~~~~~~~~~~~~~~~~~~~~~
My code is taken right from the doc and looks like this:
index.ts
import fastify from 'fastify'
const server = fastify()
server.get('/ping', async (request, reply) => {
return 'pongn'
})
interface IQuerystring {
username: string;
password: string;
}
interface IHeaders {
'h-Custom': string;
}
interface IReply {
200: { success: boolean };
302: { url: string };
'4xx': { error: string };
}
server.get<{
Querystring: IQuerystring,
Headers: IHeaders,
Reply: IReply
}>('/auth', {
preValidation: (request, reply, done) => {
const { username, password } = request.query
done(username !== 'admin' ? new Error('Must be admin') : undefined) // only validate `admin` account
}
}, async (request, reply) => {
const customerHeader = request.headers['h-Custom']
// do something with request data
return `logged in!`
})
server.listen({ port: 8080 }, (err, address) => {
if (err) {
console.error(err)
process.exit(1)
}
console.log(`Server listening at ${address}`)
})
I feel like I’m missing something obvious…
I figured it out and it was something obvious. The problem was the return 'logged in!'
– typescript detected that it was not a valid return as the Reply type needed to be “IReply”. Commenting out that line fixed my issue and my tests are now succeeding.