0

I have this piece of code in Express TypeScript

import { Router } from "express";

export const skillsRouter = Router()

skillsRouter.use((req, res, next) => {}) // Typescript knows the types of req, res and next
skillsRouter.use((err, req, res, next) => {}) // TypeScript throws implicit any error 

skillsRouter.get("/", (req, res) => {
    res.status(200).json("ok")
}) // Typescript again knows the types of req and res

Why doesn't it know the types of the Error handler params

Also I'm aware that this will fix it

skillsRouter.use(((err, req, res, next) => {}) as ErrorRequestHandler)

or this

skillsRouter.use((err: unknown, req: Request, res: Response, next: NextFunction) => {})
4
  • I never used error handling in that way on express but this should answer it quite well stackoverflow.com/questions/50218878/… Commented May 10, 2024 at 18:00
  • Looked at the link but none of the answers there explain what I'm asking. I'm asking why Typescript doesn't infer the types the function when there are 4 arguments as in an error handler? Commented May 10, 2024 at 20:19
  • i don't know why its like that but if you look at the source code use just has the types for handler not for error handler so have to explicitly type it, not ideal but its as it is, you can overwrite types if you want to. Commented May 10, 2024 at 20:35
  • I've been looking at the source, it's a bit hard to grasp since I'm still learning typescript but I've messed with the source code in my node_modules and after commenting out some portions of it, typescript is able to infer types for the error handler but unable to detect for the other overloads, ie (req, res) and (req, res, next). Commented May 10, 2024 at 23:46

0

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.