[Fixed] Express Typescript use the correct types for error middleware

Issue

Trying to get my types correct in express. I have the following middleware error function. I cannot seem to get the types correct or find an example somewhere. I have tried a lot but this is my latest version:

import express from "express";

const router = express.Router();

router.use((err:  ErrorRequestHandler, req: Request, res: Response, next: NextFunction) => {
    console.log(err);

    return res.json({
        success: false,
        message: "server err"
    });
});

Any ideas how to get the correct types for this kind of functionality?

Solution

You need to import these types from express.

import express, {ErrorRequestHandler, Request, Response, NextFunction} from 'express';

Leave a Reply

(*) Required, Your email will not be published