使用express-validator typescript定义

我试图将我的一些代码转换为TypeScript,但是在express-validator定义方面存在问题

我的代码如下所示:

///<reference path='../../../d.ts/node.d.ts' /> ///<reference path='../../../d.ts/express.d.ts' /> ///<reference path='../../../d.ts/express-validator.d.ts' /> import express = require('express'); import validator = require('express-validator'); function validate(req: express.Request, res: express.Response) { req.assert('name', 'Name is required').notEmpty(); var errors = req.validationErrors(); if (errors !== null && errors.length > 0) { res.json({ result: false, errors: errors }); return false; } return true; } 

Typescript编译器生成以下错误:

 error TS2094: The property 'assert' does not exist on value of type 'express.Request'. error TS2094: The property 'validationErrors' does not exist on value of type 'express.Request'. 

这是有道理的,特别是看看expreess-validator的定义

 export interface RequestValidation { check(field: string, message: string): Validator; assert(field: string, message: string): Validator; sanitize(field: string): Sanitizer; onValidationError(func: (msg: string) => void): void; } 

我对RequestValidation接口的理解是它必须扩展express.Request接口,但是修改这个接口声明并没有什么帮助。

我是我做错了什么?

谢谢!

在我看来,Express Validator库扩展了Express Request对象。 即它将在Express中定义的现有Request添加其他方法。

免责声明:我一直没有find任何有关Express Validator库的良好文档,如果有人有链接,我可以更确切地说。

考虑到这一点,如果Express Validator库扩展了Express Request接口,则定义应该反映这一点。 下面是一个扩展Express和Express Validator定义的例子。

 declare module Express { interface Request extends ExpressValidator.RequestValidation { } } 

这将解决与assert的问题,例如 – 如果有人发现一些文档,我希望validatonErrors问题可以用类似的方式解决。

我有一个帮助function ,检查request对象上的'id' param 。 在TypeScript 1.5.0-beta上正确运行的声明是:

 // Somewhere at the top of your TypeScript code /// <reference path="../../../../typings/tsd.d.ts" /> import ExpressValidator = require('express-validator'); import util = require('util'); 

和我使用的帮手function:

 function getOnePreconditions(req:ExpressValidator.RequestValidation, res:express.Response, next:Function) { req.checkParams('id', 'Parameter Id is mandatory').notEmpty().isInt(); var errors = req.validationErrors(); if (errors) { res.send(400, 'errors' + util.inspect(errors)); } else { next(); } } 

如果您确实为项目定义了tsd.json ,并且正确地引用了代码中的*.d.ts TypeScript定义文件,那么必须使用以下命令来添加express-validator的声明文件:

 tsd install express-validator --save