Abazhenov / express-async-handler

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

fix: handler return typings #54

Open fahmidyt opened 2 years ago

fahmidyt commented 2 years ago

Adding handler return typings core.Response | Promise<core.Response>. This fixed the issue where the handler had return res.status(200).json(anyres)

something like this

route.get(
  '/route',
  AsyncHandler(async function getAll(
    req: Request,
    res: Response
  ): Promise<Response> {
    ...
    return res.status(200).json(httpRes)
  })
)
abaumg commented 6 months ago

As a workaround for the issue discussed in this PR, you can use a TypeScript declaration file.

To use this workaround in your project, add this expressAsyncHandler.d.ts file to your project's root directory or in a directory where TypeScript can find it (like a types directory). Remember to ensure that your tsconfig.json file includes the directory where you placed the expressAsyncHandler.d.ts file in its "include" array, so TypeScript includes it in its type checking and autocompletion.

// expressAsyncHandler.d.ts

import "express-async-handler";

import express = require("express");
import core = require("express-serve-static-core");

declare module "express-async-handler" {
  declare function expressAsyncHandler<
    P = core.ParamsDictionary,
    ResBody = any,
    ReqBody = any,
    ReqQuery = core.Query,
>(handler: (...args: Parameters<express.RequestHandler<P, ResBody, ReqBody, ReqQuery>>) => void | Promise<void> | core.Response | Promise<core.Response>):
  express.RequestHandler<P, ResBody, ReqBody, ReqQuery>;    
  export default expressAsyncHandler;
}