Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return type for Express routes with TypeScript

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:

  • The easy fix is to make the route return any, but I want to avoid that if possible
  • I've seen code that does as unknown as Response but that seems like a hack

What is the correct way to declare routes' return types, without using any?

like image 938
lonix Avatar asked Feb 09 '19 05:02

lonix


People also ask

Can Express be used with TypeScript?

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.

What is Req Res next?

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.

What is route path in Express?

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.


Video Answer


1 Answers

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).

like image 151
lonix Avatar answered Nov 10 '22 22:11

lonix