我有以下 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/