ExpressJS 4 error middleware function is not recognized by TypeScript

20 Views Asked by At

ExpressJS error middleware functions need 4 parameters (err, req, res, next) instead of the usual 3 (res, res, next) in order to work.

// @ts-ignore
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});

The middleware works perfectly, but as you can see, I need to add the // @ts-ignore comment in order to have the code compiled and avoid my editor showing the errors. This happens because in my tsconfig.json I have strict: true which includes noImplicitAny : true, which I want.

But as I have "@types/express": "^4.17.21" installed and added to my devDependencies on package.json, I don't understand why ExpressJS doesn't infer automatically the parameter types of the function the same way it does when there are only 3 parameters.

I have "express": "^4.18.2", by the way.

Any ideas? Thank you.

0

There are 0 best solutions below