Using declaration merging to alter overload of `next` function in Express

Viewed 24

I would like to alter the type definition for the NextFunction when using Express, so that when invoking next() with an argument to trigger the global error handler, Intellisense can show the properties for the object that my error handler is expecting.

I have the following interface for what an object passed in to next should look like:

interface MiddlewareError {
  msg: string,
  err: Error | string,
  code?: number
}

Express already has a definition for NextFunction that takes in an err parameter of type any, but I want to augment it so that instead, the err parameter uses my MiddlewareError type.


I tried adding this to a custom type definition file:

declare module 'express-serve-static-core' {
  export interface NextFunction {
    (err?: MiddlewareError): void;
  }
}

And it does work initially when I just write out next(), but as soon as I pass in an argument, it reverts back to the original type definition:

Invoking next with no argument

Invoking next with object argument


Is it possible to do this without doing something like copying/modifying the entire Express declaration file and using that instead? It would be very helpful to be able to see what should be passed to the next function instead of having to just remember, especially when working with multiple developers.

0 Answers
Related