When writing Express middleware, I am facing challenges in deciding how to properly typecast my functions. For instance, when working on an error handler:
export function errorHandler(err, req, res, next) {
...
}
TypeScript correctly points out that the arguments are of type any, so I cast them using ErrorRequestHandler
from @types/express
:
export function errorHandler(err, req, res, next) {
...
} as ErrorRequestHandler;
However, due to precedence issues, this casting is misunderstood, leading me to put it within parentheses:
export (function errorHandler(err, req, res, next) {
...
} as ErrorRequestHandler);
This resolves the type errors but transforms the function declaration into a named function expression, making it unexportable and visually unappealing. So now I'm stuck in a dilemma - how can I properly cast my error handler while still being able to export it? Would I need to resort to the old <>
syntax?