DEV Community

Cover image for Using Typescript in a Node Project
Luis Esteban Saravia M
Luis Esteban Saravia M

Posted on

Using Typescript in a Node Project

I've been in the software industry for more than 15 years, most of that time, from one way or another, I always have to use javascript for the frontend or backend, but always feels I'm missing something, the language is not excellent enough to apply the uncle Bob suggestions, for example defining interfaces.

For that reason and a lot more, I've decided to move forward and start to use typescript in all my professional work, that reason can be a post itself, but in this post, I going to explain how you can create an Express Application using typescript from the beginning.

Let's get started.

First of all, we have to create a brand new project using yarn but if you prefer you can use Npm, that is completely up to you.

mkdir ts-node-app

cd ts-node-app

yarn init -y
Enter fullscreen mode Exit fullscreen mode

Adding the necessary dependencies

In first place we will add express.

yarn add express
Enter fullscreen mode Exit fullscreen mode

Now we will add the support for typescript. in order to do that let add some other dependencies.

yarn add typescript ts-node @types/node @types/express --dev
Enter fullscreen mode Exit fullscreen mode

typescript is installed as a dev dependency because all your code will be compilated into vanilla js, the that dependencies will be unnecessary once you build your application

Let's configure your app to use typescript.

To start using typescript in your project is not enough to install it as a dependency; you have to create a configuration file called tsconfig.json; in this file, there are a lot of configurations the most of that commented, to understand this file, please check this Link

to create the tsconfig.json you can use npx

npx tsc --init
Enter fullscreen mode Exit fullscreen mode

Now we are ready to write code using Typescript.

let's create a simple server using express and typescript.

import express from "express";

const app: express.Application = express();

app.get("/", (request: express.Request, response: express.Response) => {
  response.send("Hello World");
});

app.listen(3000, () => {
  console.log("Listening on port 3000");
});

Enter fullscreen mode Exit fullscreen mode

Building the app.

Now we are in position to build the app, so we will create a build and start scripts in package.json

"scripts": {
    "build": "tsc --project ./",
    "start": "node ./build/app.js"
  },
Enter fullscreen mode Exit fullscreen mode

Github Repo

I've put a complete version of code in my github account, here is the Link

Top comments (0)