-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Description
Prerequisites
- I have written a descriptive issue title
- I have searched existing issues to ensure the feature has not already been requested
🚀 Feature Proposal
Sorry for the wordy title. The issue occurs because assigning the handler to a variable, does not allow typescript to pass the schema inferrence into the handlers, so instead it infers it out of the handler.
Basically, the type for the schema comes from the handlers instead of from the schema property.
This can finally be fixed in Typescript 5.4 with the NoInfer utility. I would be happy to make the PR for this, along with the tests, of course. Would this be better suited for the 5.x branch or should it be a fix for 4.x?
Motivation
Basically, when using an auxilliary hook handler, the schema inferrence breaks down and makes it impossible to have proper type inference with auxilliary handlers without ugly work arounds (shown in example).
Example
Example with typebox, but any schema provider has this issue:
const schema = { querystring: Type.Object({ test: Type.String() }) };
const onRequest = async (req: FastifyRequest, reply: FastifyReply) => { };
fastify.get(
'/',
{ onRequest: onRequest, schema: schema },
async (req, reply) => {
req.query; // says unknown, but should be { test: string }
}
);
// fixed by inlining
fastify.get(
'/',
{
onRequest:async (req: FastifyRequest, reply: FastifyReply) => {},
schema: schema,
},
async (req, reply) => {
req.query; // says { test: string } as expected
}
);
// fixed with casting
const onRequest = async (req_: unknown, reply_: unknown) => {
const req = req_ as FastifyRequest, reply = reply_ as FastifyReply;
};
fastify.get(
'/',
{ onRequest: onRequest, schema: schema },
async (req, reply) => {
req.query; // says { test: string }
}
);