javascriptnode.jstypescriptexpress

Setting the type of an anonymous function TypeScript


I have an anonymous function in Express like so:

app.use((err, req, res, next) => {
  // ...
});

and I want to set the type of the function to ErrorRequestHandler (Not the return type!).

I can do it like this:

const X: ErrorRequestHandler = (err, req, res, next) => {
  // ...
}
app.use(X);

But is there a syntax to do it inline? Like this:

app.use((err, req, res, next) => {
  // ...
} : ErrorRequestHandler); // Note: this doesn't work.

Solution

  • You just need to use some extra brackets to help Typescript out.

    eg..

    app.use(<ErrorRequestHandler>((err, req, res, next) => {
    }));
    

    You can of course use as too, to avoid any JSX confusion.

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

    Notice how above the whole function is enclosed inside brackets, this allows Typescript to apply the typecast to the whole function expression.

    Code completion on req, res, & next will then work as expected.