This post is also available in: esEspañol (Spanish)

One of the most popular extensions of JavaScript is Typescript. It’s a superset of JavaScript that allows for type checking, error checking, and compilation into previous versions of JavaScript for compatibility with different environments such as browser and server apps. In this tutorial, we’ll go over how to use Typescript with Express. The source code can be found here and courses can be found here.

Project Setup

In order to get started, first, we must create our directory.

mkdir express-typescript && cd express-typescript

Now we must create our initialize our Node.JS app and setup compatibility with Typescript. This assumes that you already have Typescript installed on your system. If not, you can install it globally with the code below.

npm install -g typescript

Now let’s install our app dependencies.

npm init
npm install --save express body-parser

npm install --save-dev @types/body-parser @types/express ts-node nodemon typescript

tsc –init

mkdir server
touch server/server.ts

This will install express, as well as typescript into our project. The server.ts file will be our entry point.

Creating Our Models

We will create model files that will be the blueprint of the data we want to return in our ExpressJS API. We’ll create a User Model under server/models/user.ts

export default class User {

    username: String;
    name: String;
    email: String;

    constructor(name: String, username: String, email: String) {
        this.name = name;
        this.username = username;
        this.email = email;
    }

    getUsername() {
        return this.username;
    }
    getName() {
        return this.name;
    }
}

You can see here that each user has a name, username, and email address.

Creating Our Controllers

If you are familiar with the MVC pattern, controllers are used to martial data inside your application. We make HTTP requests to the controller, get data from a data source if one is available and then we return that data to the user.

Here we will create controller file under server/controllers/home.ts

import { Request, Response } from "express";

import User from '../models/user';
/* GET home page. */
export let index = (req: Request, res: Response) => {
    let languages = [
        {
            language: 'Spanish'
        },
        {
            language: "French"
        },
        {
            langauge: "German"
        }
    ];
    res.json(languages);
};

export let users = (req: Request, res: Response) => {

    let users = [
        new User('James Coonce', 'jcoonce', 'james@none.com'),
        new User('Jim Coonce', 'jimcoonce', 'jim@none.com'),
        new User('Norman', 'jcoonce', 'norman@none.com'),
    ];

    res.json(users);
};

export let create = (req: Request, res: Response) => {
    let user = new User(req.body.name, req.body.username, req.body.email);
    res.json(user);
};

We export the different methods to later be used in our server.ts file

import express from "express";
import bodyParser from "body-parser";

// Controllers (route handlers)
import * as homeController from "./controllers/home";

const server = express();

server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));


server.get('/', homeController.index);
server.get('/users', homeController.users);
server.post('/users/create', homeController.create);

server.listen(3000, function () {
    console.log('Example app listening on port 3000!')
});

Running Our ExpressJS Application

Now that we have our Express API laid out, let’s run our application. Modify our tsconfig file to allow for us to run our app from the command line.

{
  "compilerOptions": {
    "target": "ES2015",   
    "module": "commonjs",
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true
  }
}

Now, when we build our application, it will build to the dist folder. Next, we must add both our build script and start script to our package.json file.

{
  "name": "express-typescript",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "nodemon dist/server.js",
    "build": "tsc"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/body-parser": "^1.17.0",
    "@types/express": "^4.11.1",
    "nodemon": "^1.17.5",
    "ts-node": "^6.0.5",
    "typescript": "^2.8.3"
  },
  "dependencies": {
    "body-parser": "^1.18.3",
    "express": "^4.16.3"
  }
}

From your command line, you can now run npm build and npm start and you should now see you API.

Typescript API

Typescript API

Conclusion

Using Typescript, there are many different ways to configure your app. You can place your controllers inside of Class files, use async/await when using request and even use frameworks like Nest.JS for a more opinionated way of building your Express app. The GitHub repo can be found here.  Also, stay tuned for courses and more tutorials on Typescript and Express.

Codebrains Newsletter

Get weekly dev news and tutorials.

Powered by ConvertKit