2016-09-23 159 views
1

所有ExpressJS和打字稿的例子我能找到使用ExpressJS在打字稿類

import * as express from "express"; 

let app = express(); 
app.use("/", express.static("/")); 

不過,我想使用類方法:

import * as express from "express"; 

export class ServerApp { 

    private app: express.Express = express(); 

    public configure { 
     this.app.use('/', express.static("/"); 
    } 
} 

試圖訪問私有的use方法變量給出參數類型警告。

我想使用強打字功能,因此private app: any將不起作用。我該如何解決這個問題,還是有更好的方法?

回答

1

根據最新的快遞類型,app的類型被稱爲Application,而不是Express。如果你把它放在一個空目錄,並做

npm install typescript 
npm install typings 
./node_modules/.bin/typings install -G dt~node 
./node_modules/.bin/typings install express 
./node_modules/.bin/tsc test.ts typings/index.d.ts 

它會工作的以下文件test.ts編譯就好

import * as express from "express"; 

export class ServerApp { 

    private app: express.Application = express(); 

    public configure() { 
     this.app.use('/', express.static("/")); 
    } 
} 

但是,有多種方法來安裝類型的快遞。如果你不需要的兼容性與打字稿< 2.0(2.0發佈前幾天),你可以

npm install typescript 
npm install @types/express 
./node_modules/.bin/tsc test.ts 

,並再次它將工作。如果你看一下安裝types-metadata.jsonexpress-serve-static-core,您會發現它使用DefinitelyTyped類型-2.0分支:

"sourceRepoURL": "https://www.github.com/DefinitelyTyped/DefinitelyTyped", 
"sourceBranch": "types-2.0", 

安裝第三種方式是

../node_modules/.bin/typings install -G dt~express 

這將會把它從主枝DefinitelyTyped,作爲@Aphelion發現的,包含problematic commit,刪除了一些use重載,導致有問題的錯誤。

+0

它確實編譯正確。但是,由於某些原因,我的工具'WebStorm'給出了這個警告,但從'express-serve-static-core'獲取了它的定義。任何想法爲什麼它會比正常的定義更喜歡這個嗎? – Aphelion

+0

這可能會導致問題:https://github.com/DefinitelyTyped/DefinitelyTyped/commit/1e92c152ee1b7af9b39f01789de37e2e463fd0de – Aphelion

+1

是的你是對的!無論我做了什麼,都可能使用DefinitelyTyped的類型2.0分支,它不包含那個提交。我更新了答案。順便說一句,我也使用WebStorm,並且它似乎只是使用node_modules和typings中安裝的任何東西。 – artem