0

TSLint warns against using the var keyword in TypeScript, so I have been using import when importing modules. However, when I do this for local modules, it gives me an error when I tried to use the module.

In a file routes/main.ts I have:

import express = require("express");
let router = express.Router();
router.get("/", (req, res, next) => { ... });

module.exports = router;

In app.ts I have:

/// <reference path="../../typings/main.d.ts" />
import express = require("express");
...
import routes = require("./routes/main");
let app = express();
app.use(routes); // The type error is here.
...

Using import routes causes the following type error when I use it with app.use(routes);:

app.ts(36,13): error TS2345: Argument of type 'typeof ".../source/server...'
is not assignable to parameter of type 'RegExp'.

To fix this I can cast it to a particular type:

app.use(<express.Router>routes);

But there are places where type casting is not as clean. I can switch to using the var keyword when I import the module:

var routes = require("./routes/main");
let app = express();
app.use(routes); // No errors.

But is there a way to satisfy both the compiler and tslint? Or should I not use the "no-var-requires": true setting in tslint when using the CommonJS module style?

1 Answer 1

1

Don't use var.
You can replace module.exports = router; with export = router; in routes/main.ts.
You have misunderstood the usage of app.use. You should use app.use("/", routes).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.