-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
[TypeScript] Allow returning Reply from handlers #3923
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
Currently, a handler is allowed to return void | Promise<RouteGeneric['Reply'] | void> , see
Line 66 in 8a2b226
| ) => void | Promise<RouteGeneric['Reply'] | void> |
This means that in an async handler, we can do this:
app.get('/', async (request, reply) => {
const result = await someWork();
if (result) {
return reply.status(201).send();
}
return reply.send();
});However, if we remove the async-await, this is now a type error. The solution is to move the return to its own line, but ideally returning the Reply object would be allowed both wrapped in a Promise and not.
(another workaround is return Promise.resolve(reply.status(201).send()) which is even weirder).
It seems to me this was considered in v4, but not acted upon (yet? 😀):
fastify/types/type-provider.d.ts
Lines 95 to 99 in 2168282
| > extends infer Return ? | |
| (void | Promise<Return | void>) | |
| // review: support both async and sync return types | |
| // (Promise<Return> | Return | Promise<void> | void) | |
| : unknown |
Motivation
Being able to return Reply from synchronous handlers makes for more concise code, and would be consistent with asynchronous handlers.
Example
See "Feature Proposal"