1

I have a function, that takes a middleware function, wraps it into a try catch block and then returns back a middleware function.

tryCatch.ts

import { Request, Response, NextFunction } from "express";

export default function tryCatch(controller: (req: Request, res: Response, next?: NextFunction) => Promise<any>) {
  return async function (req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      await controller(req, res, next);
    } catch (error) {
      // do some logging first, then call next
      return next(error);
    }
  }
};

Route handler

import express from 'express';
import tryCatch from './tryCatch';
import someAsyncHandler from './controller/someAsyncHandler';

const router = express.Router({ mergeParams: true });
router.post('/foo', someAsyncHandler);
//                  ^ this works
router.post('/bar', tryCatch( someAsyncHandler ));
//                  ^ this doesn't work

It gives the following error:

No overload matches this call. The last overload gave the following error.

Argument of type '(req: Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>, res: Response<any, Record<string, any>>, next: NextFunction) => Promise<...>' is not assignable to parameter of type 'Application<Record<string, any>>'.

Type '(req: Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>, res: Response<any, Record<string, any>>, next: NextFunction) => Promise<...>' is missing the following properties from type 'Application<Record<string, any>>': init, defaultConfiguration, engine, set, and 63 more. ts(2769)

Before switching to Typescript, this worked fine. What am I doing wrong or is it just Typescript?

1 Answer 1

1

So I found out, what the issue was. As it often is, it was something completely different.

The actual issue was that I am using ts-node and it didn't recognize the declaration merging I did for the Response type. Funny enough, VS Code was able to recognize the correct types.

The solution was to add the --files flag to the command (see this answer). For reference, here are my settings.

package.json

{
  "scripts": {
    "dev": "nodemon"
  }
}

nodemon.json

{
  "watch": ["src"],
  "ext": "ts,json,js",
  "ignore": ["src/**/*.spec.ts"],
  "exec": "ts-node --files src/app.ts"
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.