gpt4 book ai didi

node.js - 如何在 Express 应用程序中使用 DefinelyTyped 定义

转载 作者:太空宇宙 更新时间:2023-11-03 23:42:02 25 4
gpt4 key购买 nike

如何将 Express 定义中的类型添加到函数中?

我有一个接受快速请求和快速响应作为参数的函数,但我无法正确设置类型。

我的标准 JS 函数如下所示:

/// <reference path="../node.d.ts" />
/// <reference path="../express.d.ts" />

function postNewGame(req, res) {

}

但我想使用快速定义中的类型来增强它。应该看起来像这样:

/// <reference path="../node.d.ts" />
/// <reference path="../express.d.ts" />

function postNewGame(req: Request, res: Response) {

}

但是让类型正常工作的正确命名空间或语法是什么?

上面的示例给出了此错误 Could not find symbol 'Request'

任何建议/帮助将不胜感激。

更新 1:

我应该注意,我尝试执行此操作的文件不是我导入 Express 模块的 app.js。我的函数位于 my-routes 内我的模块require ins 我的 app.js,这可能是我的问题。

更新 2:

我制作了一个更简单的示例应用程序来测试它,但我仍然得到 Could not find symbol 'Request'在我的 games.ts 文件中。

我的项目结构是这样的:

  • .ts-定义
    • express.d.ts
    • node.d.ts
  • 路线
    • 游戏.ts
  • app.ts

我的app.ts看起来像这样( super 简化):

/// <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') 的文件中有效。

最佳答案

即使在仅使用接口(interface)/类型的文件中,您也可以使用importexpress = require('express');。当你编译文件时,如果你实际上没有使用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');
});
}

关于node.js - 如何在 Express 应用程序中使用 DefinelyTyped 定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21797632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com