node.js - 使用TypeScript的Express路由的返回类型

标签 node.js typescript express

我正在尝试使用TypeScript来发挥其全部潜力,因此,如果可能的话,我会避免使用any

我已经看到Express路由的定义如下:

import { Request, Response } from "express";

myRouter.route("/foo").post((req: Request, res: Response): Response => {
  return res.send("Hello World");
});

之所以可行,是因为send()返回一个明确的Response

但是,如果我进行重定向:
myRouter.route("/bar").post((req: Request, res: Response): Response => {
  return res.redirect("/baz");         // redirect() returns void!
});

那不会编译,因为redirect()返回void,而不是Response

选项:
  • 简单的解决方法是使路由返回any,但如果可能的话,我想避免这种情况
  • 我见过执行as unknown as Response的代码,但看起来像是hack

  • 不使用any声明路由返回类型的正确方法是什么?

    最佳答案

    根据@jfriend的评论,回调的declaration for RequestHandler为:

    (req: Request, res: Response, next: NextFunction): any;
    

    因此,在这种情况下使用any是可以的。

    但是,将其声明为void可能会更好,因为Express并不期望返回值。这就是我正在做的事情,并且我认为此处的输入是“错误的”(如果不是这种情况,并且存在有效的用例,请告诉我)。

    关于node.js - 使用TypeScript的Express路由的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54603561/

    相关文章:

    javascript - 将 Node Express 服务器上长时间运行的异步函数的进度数据发送到 React 客户端

    node.js - 如何在 Atom 中安装 Jade 语言支持

    javascript - Mongodb 将变量设置为 find().toarray()

    ios - Apple Pay - "Payment Not Completed"- 使用 Stripe

    javascript - Angular 4 @HostBinding ('attr.id' )不起作用(未定义)

    typescript - 如何在 typescript 中组织我的类型/接口(interface)声明?

    typescript - ngCordova 的输入似乎丢失了

    node.js如何在中间件中从redis数据库中获取数据

    javascript - 如何在 Node 中使用全局 URLSearchParams

    javascript - 如何在 Handlebars 和 Puppeteer 中使用自定义字体?