Set up NodeJs Express with Typescript

Cheulong Sear
3 min readApr 22, 2022

--

I assume that you already have at least the basic knowledge of NodeJs and Typescript.

Before, we start. Please make your devices has typescript and touch-cli install globally. If not, you can run command yarn global add typescript touch-cli.

  • typescript — to be able to use tsc command.
  • touch-cli — to be able to implement the touch command for Node.

Frist, create a new nodejs project

npm init -y

It will create package.json

Next, add dependencies

yarn add -D typescript express ts-node nodemon @types/node @types/express
  • typescript — to code typescript in the project.
  • express— to make the route for api request.
  • ts-node— to be able to run node app in typescript directly without the precompilation.
  • nodemon— to watch the server and rerun when the code changes.
  • @types/node— to be able to use custom typescript types for node.
  • @types/express— to be able to use custom typescript types for express.

Now, you can run tsc --init to create typescript config file. Then let change target to es6 and outDir to ./dist

After that, we create app.ts file

mkdir src && cd src && touch app.ts

Before, we can test if typescript works, we need to add some commands to script.

  • node dist/app.js — to run the node app in javescript.
  • nodemon src/app.ts — to run the node app in typescript.
  • tsc -p . — to compile the typescript.

Next, we add basic express code to app.ts

We can importApplication, Request, Response from express because we already install types/express .

Now, when you run yarn dev . We will see

You successfully run node typescript.

Finally, let build our nodejs app by running command yarn build

Notice that app.js is written in es6.

Let test running our final nodejs project’s result by running yarn start . You will see the same result.

Congratulations, you successfully add typescript to nodejs project.

The repository for this article https://github.com/cheulong/setup-node-ts

--

--

Cheulong Sear

Frontend Developer at Seven Peaks Software, looking to learn new thing and language enthusiast. ^^