Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - Importing Express not working

I have this in my app with the @types/express dependency installed

import express = require('express');

It is pointing to the express and saying this is an unexpected identifier when I run my server. I believe this is correct TS syntax and the regular JS way of const express = .. has the same error.

Do I need regular express? or wouldn't I need the one I already installed, which should be for TS specifically?

like image 392
mph85 Avatar asked Jul 04 '19 03:07

mph85


People also ask

Does Express work with TypeScript?

Installing TypeScript Along with it, we'll install the the @types declaration packages for Express and Node. js, which provide type definitions in the form of declaration files. Declaration files are predefined modules that describe the shape of JavaScript values, or the types present, for the TypeScript compiler.

Can you use TypeScript with Nodejs?

TypeScript is well-established in the Node. js world and used by many companies, open-source projects, tools and frameworks. Some of the notable examples of open-source projects using TypeScript are: NestJS - robust and fully-featured framework that makes creating scalable and well-architected systems easy and pleasant.

Is JavaScript faster than TypeScript?

JavaScript though it is very popular and is the slowest language that takes a lot of time to the execution the commands. Instead, the Typescript is much faster and more efficient as compared to JavaScript both in terms of speed of execution and the scaling of devices as well.


2 Answers

The syntax you want will be

import express from "express";

and it shouldn't result in a duplicate identifier error unless its simply a IDE bug. You can look into a common setup most people use to work with NodeJS/Typescript here.

https://github.com/microsoft/TypeScript-Node-Starter

like image 124
Shanon Jackson Avatar answered Oct 21 '22 16:10

Shanon Jackson


To replace require statement with import statement, for example:

    const express = require('express');

You can convert it to this:

    import * as express from "express";

And yes, you need both, regular express as dependency and @types/express as dev-dependency to have TypeScript type definitions working.

like image 42
Nenad Avatar answered Oct 21 '22 16:10

Nenad