如何在Express应用程序中使用DefinitetlyTyped定义
如何将Express定义中的types添加到函数中?
我有一个function,需要快速请求和快速响应作为参数,但我无法正确设置types。
我的标准JS函数看起来像这样:
/// <reference path="../node.d.ts" /> /// <reference path="../express.d.ts" /> function postNewGame(req, res) { }
但是我想用Express定义的types来增强它。 应该看起来像这样:
/// <reference path="../node.d.ts" /> /// <reference path="../express.d.ts" /> function postNewGame(req: Request, res: Response) { }
但是,我是什么正确的命名空间或语法才能使types工作?
上面的示例给出了这个错误Could not find symbol 'Request'
任何意见/帮助将不胜感激。
更新1 :
我应该注意到,我正在尝试这样做的文件不是app.js,我导入快速模块。 我的函数驻留在my-routes
模块中,我require
我的app.js,这可能是我的问题。
更新2 :
我做了一个更简单的示例应用程序来testing这个,我仍然Could not find symbol 'Request'
在我的games.ts文件。
我的项目结构是这样的:
- .TS-定义
- express.d.ts
- node.d.ts
- 路线
- games.ts
- app.ts
我的app.ts看起来像这样(超简化):
/// <reference path=".ts-definitions/express.d.ts" /> var express = require('express') var app = express(); require('./routes/games')(app); http.createServer(app).listen(app.get('port'), function () { console.log("Express server listening on port " + app.get('port')); });
和我的games.ts像这样:
/// <reference path="../.ts-definitions/express.d.ts" /> // How do i access express.Request, when express is not defined in the file? module.exports = function (app) { app.get('/games', function (req: express.Request, res: express.Response) { // express is not defined res.render('games'); }); }
对我来说,似乎只有在我有import express = require('express')
的文件中才有定义
你可以使用import express = require('express');
即使在只使用接口/types的文件中也是如此。 当你编译这个文件时,如果你实际上没有使用express,那么TypeScript编译器足够聪明,可以将它从编译好的代码中删除。
/// <reference path="../.ts-definitions/express.d.ts" /> import express = require('express'); module.exports = function (app) { app.get('/games', function (req: express.Request, res: express.Response) { res.render('games'); }); }
看看我写的纯TypeScript编写的示例Express应用程序,你应该能够得到如何pipe理你的文件在那里的要点: https : //github.com/czechboy0/Express-4x-Typescript-Sample
(另外,使用tsd,而不是手动添加types标题,将为您节省大量的时间。)
- TypeScript编译器很慢(6-10s)
- 用于angular度2/4项目的自定义日志文件
- Firebase admin.auth.createUser错误(nodejs + Typescript + firebase-admin)
- 如何指定我想在Typescript中重载的函数?
- npm找不到js文件
- angular度谷歌login模块投掷404
- 如何将第三方Javascript文件导入到IntelliJ中,以便我可以在一个Typescript文件中引用它
- 文件之间的NodeJs TypeScript命名空间
- 用于存储与PHP $ _sessionvariables相同的Angular session值的variables