Abazhenov / express-async-handler

Async Error Handling Middleware for Express
572 stars 39 forks source link

fix: Add missing typings for express response Locals #50

Open danmana opened 2 years ago

danmana commented 2 years ago

Express RequestHandler has a fifth generic Locals that controls the typing of the res.locals property.

With the current version of express-async-handler it's impossible to pass that generic.

interface MyLocals {
  something: number;
}

router.get('test', expressAsyncHandler(async (req, res: Response<any, MyLocals>) => {
    res.locals.something = 5;
    res.locals.somethingElse = 6;
  })
);

Without this fix it shows an error: image

Argument of type '(req: Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>, res: Response<any, MyLocals>) => Promise<...>' is not assignable to parameter of type '(req: Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>, res: Response<any, Record<string, any>, number>, next: NextFunction) => void | Promise<...>'.
  Types of parameters 'res' and 'res' are incompatible.
    Type 'Response<any, Record<string, any>, number>' is not assignable to type 'Response<any, MyLocals>'.
      Types of property 'locals' are incompatible.
        Property 'something' is missing in type 'Record<string, any>' but required in type 'MyLocals'.ts(2345)

With the Locals generic it works as expected image