How to Add TypeScript Types 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

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.