Search code examples
node.jstypescriptexpressnode-modulesrequire

Why do these 2 NodeJS / Typescript imports give different results?


In a NodeJS project, I have installed typescript 3.2, express 4.16 and @types/express 4.16

I am writing my application in Typescript to be later transpiled. The documentation for @types/express say to import and use this way:

import * as express from "express";
const app = express();

However when I do this, the 2nd line throws an error because express is not a function (does not have a call signature). When I console log express I get an object with an application property

On the other hand, if I import and use this way:

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

Then everything works and console-logging express shows a function called createApplication or something similar. The function itself seems to have the same application property from the 1st method.

What is the difference?


Solution

  • As of TypeScript@2.7 the following syntax for importing default module is supported:

    import b from "bar";
    

    Your example with * will import all of a module's exports as a module object but you probabaly want

    import express from "express";
    const app = express();