[英]expressjs: typescript: Argument of type 'typeof <express.Router>' is not assignable to parameter of type 'RequestHandlerParams'
I am using expressjs with the latest typescript definition file and typescript 2.3.4 from https://github.com/DefinitelyTyped/DefinitelyTyped .我正在使用 expressjs 和来自https://github.com/DefinitelyTyped/DefinitelyTyped的最新打字稿定义文件和打字稿 2.3.4。 I defined a router and would like to use it from a subpath as is stated in the official 4.x documentation (
app.use('/calendar', router);
), but I get following error我定义了一个路由器,并希望按照官方 4.x 文档(
app.use('/calendar', router);
)中所述从子路径使用它,但出现以下错误
Error: /Users/matthias/Documents/private workspace/universal/src/server/server.ts (161,34): Argument of type 'typeof "/Users/matthias/Documents/private workspace/universal/src/server/routes/login.router"' is not assignable to parameter of type 'RequestHandlerParams'.
Type 'typeof "/Users/matthias/Documents/private workspace/universal/src/server/routes/login.router"' is not assignable to type '(RequestHandler | ErrorRequestHandler)[]'.
Property 'length' is missing in type 'typeof "/Users/matthias/Documents/private workspace/universal/src/server/routes/login.router"'.
This is the router I am using, ommiting the actual code...这是我正在使用的路由器,省略了实际代码...
const router : express.Router = express.Router();
let loginController = new LoginController();
router.post('/signin', function(req: express.Request, res: express.Response, next: express.NextFunction) {
...
})(req, res, next);
});
...
export default router;
... and this is the shortened version of the call to it. ...这是对它的调用的缩短版本。
import * as loginRouter from './routes/login.router';
private app = express();
this.app.use('/api/v1/auth', loginRouter);
Am I doing something wrong or is this usecase just not properly defined in the typescript definition files?我做错了什么还是这个用例只是在打字稿定义文件中没有正确定义?
Kind Regards亲切的问候
Found it, import * as ... seems to lose its typescript information (IRouter, Router)找到了,import * as ... 好像丢了打字稿信息(IRouter,Router)
Solution is to use import loginRouter from './routes/login.router';
解决方案是使用
import loginRouter from './routes/login.router';
instead反而
I fixed this issue by removing我通过删除解决了这个问题
export default router;
at the end of my router module.在我的路由器模块的末尾。 I simply exported it where I created it
我只是将它导出到我创建它的地方
export const router = express.Router();
and then updated any imports of the module accordingly.然后相应地更新模块的任何导入。
I don't know why the compiler had trouble with the default export, but I know that TypeScript's default exports are not identical to ECMAScript's default exports.我不知道为什么编译器在默认导出时遇到问题,但我知道 TypeScript 的默认导出与 ECMAScript 的默认导出不同。
I was doing silly mistake and waited for a long time to check solution我犯了愚蠢的错误,等了很长时间来检查解决方案
I was using an app
property as a method我使用
app
属性作为方法
app('/account', accountRoutes)
but I need to use use()
method instead但我需要改用
use()
方法
app.use('/account', accountRoutes)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.