将 Express() 与 TypeScript 结合使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12710063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 16:11:48  来源:igfitidea点击:

Using Express() with TypeScript

node.jsexpresstypescript

提问by Zoltan Arvai

I want to use the most recent version of Expess with node.js in TypeScript. The express.d.ts provided by microsoft in the samples seems to be built upon a versions prior to 3.0.x. In previous version you could do

我想在 TypeScript 中使用带有 node.js 的最新版本的 Expess。微软在示例中提供的 express.d.ts 似乎是基于 3.0.x 之前的版本构建的。在以前的版本中,您可以这样做

var app = express.createServer()

but after 3.0.x you should do:

但在 3.0.x 之后你应该这样做:

var app = express();

Express.d.ts does not support this... I've found a hack around this: I've added the following line to Express.d.ts:

Express.d.ts 不支持这个......我发现了一个解决这个问题的技巧:我在 Express.d.ts 中添加了以下行:

export function(): any;

In app.tswhen I want to create the app object I do the following:

app.ts当我要创建应用程序对象我做到以下几点:

var app = <express.ExpressServer>express();

This seems to fix the issue, it's compiling without an error, and also I get intellisense support. However this is a hack... First of all why can't I write something like this?

这似乎解决了这个问题,它编译没有错误,而且我得到了智能感知支持。然而这是一个黑客......首先为什么我不能写这样的东西?

export function(): ExpressServer;

Is this the recommended way to fix this issue?

这是解决此问题的推荐方法吗?

回答by Wade Hatler

Pretty old discussion, but I ran into the same problem recently and found that there is a new express.d.tsthat properly supports express 3 on the DefinitelyTypedsite.

很老的讨论,但我最近遇到了同样的问题,发现express.d.ts绝对类型站点上有一个正确支持 express 3的新问题。

回答by joshuapoehls

You should be able to add this ambient function declaration to express.d.tsto get what you want.

您应该能够添加此环境函数声明express.d.ts以获得您想要的。

declare function express(): ExpressServer;

declare function express(): ExpressServer;

回答by MajidJafari

if you declare expressthis way: import * as express from "express", you will get this error in runtime, declaring it this way: const express = require "express", won't throw any error.

如果你这样声明express: import * as express from "express",你会在运行时得到这个错误,这样声明它: const express = require "express",不会抛出任何错误。

Also, don't forget to declare appvariable or property type as express.Application

另外,不要忘记将app变量或属性类型声明为express.Application

回答by czechboy

Here's a sample project - Express 4.x app in TypeScript: https://github.com/czechboy0/Express-4x-Typescript-Sample

这是一个示例项目 - TypeScript 中的 Express 4.x 应用程序:https: //github.com/czechboy0/Express-4x-Typescript-Sample