Building applications with Node & TypeScript

I have been working with TypeScript for almost 2 years, using it in both frontend and backend. In my opinion, TypeScript makes developers life easier, especially when they have a OOP background.

But why TypeScript?

First of all “how cool is it to have types in JavaScript?” Answer: It’s awesome!!!

It’s very important to have types when writing complex applications or libraries. Types can avoid mistakes and, in my opinion, make the code more readable. Secondly, TypeScript is maintained by Microsoft and they are doing an excellent job updating the language to support the lastest EcmaScript features. Lastly, TypeScript supports all features from ES5, ES2015 and much more: types, generics, enums, interfaces etc…

PS: If you have a few minutes, this post from André Staltz is worth a read – “All JS Libraries should be authored in TypeScript”.

Now that I have made an introduction about my experience with TypeScript, I will show you how to create a simple api using hapi.js and TypeScript.

Setup the environment

Install Typescript: npm install -g typescript
Install Typings: npm install -g typings
Text editor that supports TypeScript: I really recommend Visual Code.

Basic concepts

Definitions

Definitions are what give you intellisense and typification. They are suffixed by “.d.ts” and to reference them it’s necessary to include them on top of the TS files by using the following sintax:

 /// <reference path="./typings/main.d.ts" />

Typings

Typings (TypeScript Definition Manager) is a tool to manage and install TypeScript definitions, and uses a typings.json file to save the dependencies similar to package.json.

Code

Before starting coding we need to install our dependencies:

  • npm init – Create package.json file
  • npm install hapi –save – Install hapi module
  • typings install node –save –ambient – Install node definition
  • typings install hapi –save –ambient – Install hapi definition

Now we can finally create our “server.ts” file and copy the following code:

PS: As we can see, the first line has the reference to our definitions installed by typings.

/// <reference path="./typings/main.d.ts" />

"use strict";

import * as Hapi from "hapi";

const server: Hapi.Server = new Hapi.Server();
server.connection({ port: 3000 });

server.route({
    method: "GET",
    path: "/{name}",
    handler: (request: Hapi.Request, reply: Hapi.IReply) => {
        reply(`Hello ${request.params["name"]}`);
    }
});

server.start((err) => {

    if (err) {
        throw err;
    }
    console.log("Server running at:", server.info.uri);
});

Compile

Let’s change our package.json and add two new tasks.

"scripts": {
   "build": "tsc", //compile the TS files to JS
   "start": "node build/server.js", //run server
}

Before compiling, it’s necessary to create a tsconfig.ts file to configure the TypeScript compiler.

{
  "compilerOptions": {
    "outDir": "build",
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true
  },
  "exclude": [
    "node_modules",
    "typings"
  ]
}

Run

Compile the project using the task that we have created npm run build, then we can check the compilation result inside the folder build.

Finally, let’s run our server npm start, and go to browser localhost:3000/Marco!

Thats it! Simple isn’t it?

If you want to know more, check out the slides from my last talk.

A complex example could be found here

I'm a Software Engineer that believes software must be simple, intuitive and reliable. My main interests are api’s design, best software practices, distributed systems and continuous integration.

Your email address will not be published. Required fields are marked *