I'm trying to write type definitions for an "async-route" wrapper for express.js. I'm new to typescript, just learned about generics.
As the function could be called behind middlewares that extend the default express Request I want to create it so users can provide their own extended "Request".
So far I have gotten to:
asyncRoute.ts
import { NextFunction } from 'express';
type Fn = <R, S>(req: R, res: S, next?: NextFunction) => Promise<any>;
export default function asyncRoute<R, S> (fn: Fn) {
return function asyncRouteWrap(req: R, res: S, next: NextFunction) {
Promise.resolve(fn<R,S>(req, res, next)).catch(next);
};
};
Usage:
import { Request } from 'express';
interface AppRequest extends Request {
log: Logger;
// ...other stuff
}
router.get(
'/',
asyncRoute<AppRequest, AppResponse>(async (req, res) => {
req.log.info('test');
})
);
But I get Property 'log' does not exist on type 'Request'.