2

In the common construct of defining nested routers in multiple files when exporting a router directly using Typescript 2 and the @types/[email protected] definition following code throws

error TS4023: Exported variable 'router' has or is using name 'Router' from external module 
         "[...]/node_modules/@types/express-serve-static-core/index" but cannot be named.

Example taken from basarat's answer

import * as express from "express";

// import sub-routers
import * as adminRouter from "./admin/admin";
import * as productRouter from "./products/products";

let router = express.Router();

// mount express paths, any addition middleware can be added as well.
// ex. router.use('/pathway', middleware_function, sub-router);

router.use('/products', productRouter);
router.use('/admin', adminRouter);

// Export the router
export = router;

1 Answer 1

14

The solution is to explicitly annotate the router variable (TypeScript/issues/5711#issuecomment-161194656).

Following code will work (note the let router: express.Router = express.Router())

import * as express from "express";

import * as adminRouter from "./admin/admin";
import * as productRouter from "./products/products";

let router: express.Router = express.Router();

router.use('/products', productRouter);
router.use('/admin', adminRouter);

// Export the router
export = router;
Sign up to request clarification or add additional context in comments.

1 Comment

what you have in your productRouter, I just tried to import router from "../app" router.get("/", (req, res) => { res.send("Hello World!"); }); export = router; and it doesn't work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.