Aphelion Aphelion - 2 months ago 34
TypeScript Question

ExpressJS in a TypeScript class

All ExpressJS and TypeScript examples I could find use

import * as express from "express";

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


However, I want to use the class approach:

import * as express from "express";

export class ServerApp {

private app: express.Express = express();

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


Trying to access the
use
method on the private variable gives an argument type warning.

I want to use strong typing so
private app: any
will not work. How can I solve this problem, or is there a better approach?

Answer

According to the latest express typings, the type for app is called Application, not Express. The following file test.ts compiles just fine

import * as express from "express";

export class ServerApp {

    private app: express.Application = express();

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

if you put it in an empty directory and do

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

it will work.

However, there is more than one way to install typings for express. If you don't need compatiblity with typescript < 2.0 (2.0 was released a few days ago), you can just

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

and again it will work. If you look at installed types-metadata.json for express-serve-static-core, you notice that it uses types-2.0 branch of DefinitelyTyped:

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

The third way to install is

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

this will take it from the main branch of DefinitelyTyped, which, as @Aphelion discovered, contains problematic commit that removes a number of use overloads, causing the error in question.