node.js - TypeScript + Express : req. 参数

标签 node.js express typescript

我有以下 express 路线:

app.get('/:id', function (req, res) {
  var idNum: number = Number(req.params.id);
  var idCast: number = +req.params.id;
  var id: number = req.params.id;

  console.log('typeof idNum ', typeof idNum , '  ', 'idNum== 0 :  ', idNum== 0  , '  ', 'idNum=== 0 :  ', idNum=== 0);
  console.log('typeof idCast', typeof idCast, '  ', 'idCast == 0 :', idCast == 0, '  ', 'idCast === 0 :', idCast === 0);
  console.log('typeof id    ', typeof id    , '  ', 'id == 0 :    ', id == 0    , '  ', 'id === 0 :'    , id === 0);

  res.json({});
});

返回:

typeof idNum  number    idNum== 0   : true    idNum=== 0   : true
typeof idCast number    idCast == 0 : true    idCast === 0 : true
typeof id     string    id == 0     : true    id === 0     : false

我知道 typescript 只提供编译时类型检查,我想这意味着它不知道 req.params 以字符串形式提供参数。

有什么方法可以自动将我的参数转换为 Number 吗?或者至少提出一个我没有手动完成的错误?否则,除非在完整的 typescript 环境中使用,否则 typescript 似乎是无用的。

最后,是否有任何使用 TypeScript 和 ExpressJS 的“大型”开源项目我可以从中读取源代码?

最佳答案

您可以输入 req通过扩展 Request 对象express 提供的类型,语法如下:

Request<Params, ResBody, ReqBody, ReqQuery>

因此,在您的示例中,您可以执行类似以下操作来显式声明您的属性是传入字符串,以确保将其转换为数字类型:

import { Request } from "express"

...

app.get('/:id', function (req: Request<{ id: string}>, res) {
  
...

关于node.js - TypeScript + Express : req. 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39348696/

相关文章:

javascript - 如何退出 .JS 进程以便它向 AHK 返回 StdOut 值?

具有通用联合约束的 TypeScript 函数返回值

typescript - 在 TypeScript 中推断函数参数

node.js - 如何使用 Mongoose findOne

node.js - 如何使用 get 库从给定的 url 下载文件到缓冲区?

node.js - 错误: INVALID_RESPONSE - Data is returning from promise but can't get Alexa to speak/show card

javascript - NodeJS + Mongo - 如何与 DOM 交互以从数据库获取数据?

node.js - 发送后无法设置标题。 express JS

node.js - 在express js中转发查询

javascript - Typescript - 如何将所有已转译的 js/map 文件定向到构建目录