Reputation: 20609
I'm trying to use TypeScript to it's full potential, so I avoid any
if possible.
I've seen Express routes defined like this:
import { Request, Response } from "express";
myRouter.route("/foo").post((req: Request, res: Response): Response => {
return res.send("Hello World");
});
That works because send()
returns an express Response
.
But if I do a redirect:
myRouter.route("/bar").post((req: Request, res: Response): Response => {
return res.redirect("/baz"); // redirect() returns void!
});
That won't compile because redirect()
returns void, not Response
.
Options:
any
, but I want to avoid that if possibleas unknown as Response
but that seems like a hackWhat is the correct way to declare routes' return types, without using any
?
Upvotes: 16
Views: 21163
Reputation: 20609
As per @jfriend's comments, the callback's declaration for RequestHandler is:
(req: Request, res: Response, next: NextFunction): any;
So using any
in this case is okay.
However, declaring it as void
may be even better as Express doesn't expect a return value. That's what I'm doing, and I'm considering the typings here to be "wrong" (if this isn't the case and there is a valid use case, please let me know).
Upvotes: 27