Typescript setup for express applications
Published: 2021-03-20 11:10:50

#### Introduction

Typescript is a superset of JavaScript that means all of the JavaScript code is valid in Typescript. The most important reason why developers like to develop their applications in Typescript is because of its strong static typing which JavaScript lacks. Typescript makes code much more easier to read as well as understand.

In this writing, I'll demonstrate how to setup a Express.js and Node.js application with Typescript support.

#### Initialize Project

Firstly, we will make the directory where in we will store our project files. Let's call it `my-node-app`, you can call it whatever you want.

```bash
mkdir my-node-app
```

Next, we will initialize a node app by running following command

```bash
yarn init -y
```

> `-y` sets all the values in `package.json` to default, you can choose not type `-y` and set all values manually.

Now, let's install typescript and other `devDependencies`.

```bash
yarn add -D typescript ts-node nodemon @types/node @types/express
```

> `-D` flag is the shorthand for --save-dev, it is used to install `devDependencies`, package managers(yarn or npm) do not install these dependencies when in production.

Now, let us understand what each of these installed dependencies do

1. `typescript` - Helps compile `.ts` files to JavaScript.
2. `ts-node` - Creates Typescript execution environment for Node.js.
3. `nodemon` - Restarts node application when changes are detected in project files.
4. `@types/node` - Type definition for Node.js modules.
5. `@types/express` - Type definition for express package.

Installing express,

```bash
yarn add express
```

Now that we have installed packages we will do some configuration to run our project.

#### Configure Typescript

In this section, we will configure Typescript for our project. Typescript uses `tsconfig.json` to configure compiler. We have to create `tsconfig.json` in our root directory, you can either manually create this file or run following command.

```bash
tsc --init
```

This will create `tsconfig.json` file for you, now just uncomment the following options

```json
{
  "compilerOptions": {
    "target": "ESNEXT",
    "module": "commonjs",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}
```

Here, `rootDir` i.e root directory is set to `src`. In `src` all of our scripts will sit. `outDir` i.e output directory is set to `dist`, here all of the compiled JavaScript will be stored.

Now, we have `tsconfig.json` set up, let's test things out.

#### Setup basic express server

Create a new file called `index.ts` in `src` directory. This will be our entry point. Write the following code in `index.ts` to test out if typescript compiler is working alright.

```typescript
// src/index.ts
const greet = (name: string): string => {
  return `Hello ${name}!`;
};

greet('John');
```

Let's compile it by running following command

```bash
tsc
```

If you notice there would be a new directory called `dist` was added in the root directory, inside this directory you can find a file called `index.js`, this is our compiled javascript. You can find following javascript code in the file.

```javascript
// dist/index.js
'use strict';

const greet = (name) => {
  return `Hello ${name}!`;
};
greet('John');
```

Now, we have checked that our compiler is running fine. Let us now add express server. Replace everything in `index.ts` with following code to setup basic express server.

```typescript
// src/index.ts

import express from 'express';

const app = express();

const server = app.listen(5555, () => {
  console.log(`⚡[server] Server listening at http://localhost:5555`);
});
```

Now, to run the code let's use `nodemon`, nodemon will watch for changes in files and restart server everytime we save a change.

```bash
nodemon src/index.ts
```

You can see server running in the terminal!

#### Add scripts to package.json

We will be adding scripts to our `package.json` for building, starting dev server and starting the application when it is in production.

```json
// package.json
...
"scripts" : {
  "dev": "nodemon src/index.ts",
  "start": "node dist/index.js",
  "build": "tsc --project ./"
}
...
```

#### Conclusion

Congratulations! We have now setup a basic express setup with typescript support. Don't forget to checkout [Typescript website](https://www.typescriptlang.org/) for more info on Typescript. Also, make sure to checkout different [Typed Definitions](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types).