Abazhenov / express-async-handler

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

Typescript types for handler arguments are "unknown" #56

Open 0x80 opened 1 year ago

0x80 commented 1 year ago

If I define a handler like this:

const router = express.Router();

router.get(
  "/verify-email",
  asyncHandler(async (req, res) => { }))

TS complains that the types of req and res are unknown and so I can't use any of their methods.

Any idea what might be causing this? I've tried both TS version 4.6 and 4.9 and using express-async-handler 1.2.0 and express 4.17.1

If I try to explicitly type req to express.Request I get "Type 'unknown' is not assignable to type 'Request"

wzomer commented 1 year ago

Same issue here, have you found any solution @0x80 ?

0x80 commented 1 year ago

@wzomer No, unfortunately not. I tried to set some yarn resolutions for types but it didn't make a difference. I am a little tired of running into typing problems with Express so I am now investigating a migration to Fastify...

Voronar commented 1 year ago

This handwritten async handler works with these package versions:

import { RequestHandler, NextFunction } from 'express';

// Generic parameters just copied from RequestHandler
export const asyncHandler = <
  P,
  ResBody,
  ReqBody,
  ReqQuery,
  LocalsObj extends Record<string, any> = Record<string, any>
>(
  fun: (...args: Parameters<RequestHandler<P, ResBody, ReqBody, ReqQuery, LocalsObj>>) => void,
) => (...args: Parameters<RequestHandler<P, ResBody, ReqBody, ReqQuery, LocalsObj>>) => {
  const next = args[args.length - 1];
  Promise.resolve(fun(...args)).catch(next as NextFunction)
}
piotrnajda3000 commented 3 months ago

I've had a small issue with the generic definition while using this, and copy-pasting definition from RequestHandler helped:

<
    P = core.ParamsDictionary,
    ResBody = any,
    ReqBody = any,
    ReqQuery = qs.ParsedQs,
    LocalsObj extends Record<string, any> = Record<string, any>
  >