打字稿 + 快递:req.params

Igg*_*ggY 6 node.js express typescript

我有以下快速路线:

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({});
});
Run Code Online (Sandbox Code Playgroud)

这返回:

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
Run Code Online (Sandbox Code Playgroud)

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

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

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

Sat*_*ors 27

您可以通过使用以下语法req扩展express提供的类型来键入对象:Request

Request<Params, ResBody, ReqBody, ReqQuery>

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

import { Request } from "express"

...

app.get('/:id', function (req: Request<{ id: string}>, res) {
  
...
Run Code Online (Sandbox Code Playgroud)


Nit*_*mer 8

似乎是req.params这样any,编译器无法知道它的值是id字符串,但当然它是一个字符串,因为它作为路径参数出现,而路径参数始终是字符串。

您应该能够使用路由器中间件来处理它,例如:

router.use(function (req, res, next) {
    if (req.params && req.params.id && typeof req.params.id === "string") {
        let num = Number(req.params.id);
        if (!isNaN(num)) {
            req.params.id = Number(req.params.id);
        }
    }
    next();
});
Run Code Online (Sandbox Code Playgroud)

这应该将所有名为 id 的参数(字符串)转换为数字。

  • 感谢您的回答,但这样做对我来说真的很脏:/ (7认同)
  • 我怀疑你会找到一种更“自动”的方式来做到这一点。中间件功能适用于像这样的情况。 (2认同)