How to Add TypeScript Types for Express.js Error Handler?

TypeScript type for Express.js error handler

In Express.js, you can add type to an error handler middleware function by importing the ErrorRequestHandler type from express package like so:

import type { ErrorRequestHandler } from 'express';

You may add the type to the error handler function in the following ways:

// ...
const errorHandler: ErrorRequestHandler = (err, req, res, next) => {};
app.use(errorHandler);
// ...
app.use(((err, req, res, next) => {}) as ErrorRequestHandler);

If you haven't installed the type definitions for Express.js, then make sure to add them to the dev dependencies list in your package.json, for example, like so:

npm install --save-dev @types/express

Hope you found this post useful. It was published . Please show your love and support by sharing this post.