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 possible as unknown as Response
but that seems like a hack What is the correct way to declare routes' return types, without using any
?
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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.