2017-08-03 32 views
0

我不知道是否有人能與導入格式幫助導入expressjs爲打字稿(我用的是@types,已經安裝)ExpressJS與Typescript,導入格式?

我導入這樣

import { Application} from "express"; 

所以在我的代碼,我可以現在做這個

private expressApp: Application; 

問題是,我想創建一個新的快遞應用程序,所以我想我必須做到以下幾點,

 this.expressApp = new Application(); 

但它報告一個錯誤,說它只是一個類型。

我有點迷路,如何正確使用它。

我也想這樣做

import * as express from "express"; 

,但現在一切都不願意去表達,所以我有express.Application這是一個有點難看。它仍然不可能做一個新快報()

任何想法,我要去的地方錯了嗎?

感謝

回答

1

這類的東西絆倒了我很多,當我正與打字稿交手,問題是你使用的「應用程序」,它實際上只是一個類型定義,而不是對象本身。你想這樣的事情:

import * as express from 'express'; 
const app: express.Application = express(); 

app.get('/', function (req, res) { 
    res.send('Hello World!'); 
}); 

app.listen(3000, function() { 
    console.log('Example app listening on port 3000!'); 
}); 

這裏我使用express.Application來表示類型。 express.Application只是一個表示類型的接口。否則,您會注意到我的代碼與Express "Hello World" example相同:

const express = require('express') 
const app = express() 

app.get('/', function (req, res) { 
    res.send('Hello World!') 
}) 

app.listen(3000, function() { 
    console.log('Example app listening on port 3000!') 
}) 
+0

謝謝。是的,有效的,任何方式來結合進口*明確表達從'快遞'和進口{應用程序}從「明確」;在一條線上? – Martin

+0

@Martin可悲的是,如果是「express」,你可以添加第二個導入。你想從鍵入中刪除。但是,由於快速功能是默認導出,您需要創建一個新的應用程序。如果這回答了你的問題,你會介意打勾嗎? –