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
?
Installing TypeScript Along with it, we'll install the the @types declaration packages for Express and Node. js, which provide type definitions in the form of declaration files. Declaration files are predefined modules that describe the shape of JavaScript values, or the types present, for the TypeScript compiler.
Middleware functions are functions that have access to the request object ( req ), the response object ( res ), and the next function in the application's request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.
Path is the route at which the request will run. Handler is a callback function that executes when a matching request type is found on the relevant route. For example, var express = require('express'); var app = express(); app.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With