Node.js with Microsoft TypeScript

Before we start let’s just ask a few questions:

Why Typescript?

There are two main goals of TypeScript:

    • Provide an optional type system for JavaScript.
    • Provide planned features from future JavaScript editions to current JavaScript engines

The TypeScript type system

You might be wondering “Why add types to JavaScript?

Types have a proven ability to enhance code quality and understandability. Large teams (Google, Microsoft, Facebook) have continually arrived at this conclusion. Specifically:

  • Types increase your agility when doing refactoring. It’s better for the compiler to catch errors than to have things fail at runtime.
  • Types are one of the best forms of documentation you can have. The function signature is a theorem and the function body is the proof.

However, types have a way of being unnecessarily ceremonious. TypeScript is very particular about keeping the barrier to entry as low as possible.

Why node.js?

Nodejs is fast, event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

Getting started

First, you will need to install TypeScript into your node environment this is as easy as just running the following commands:

$ npm init -y
$ npm install -g typescript

This will give your terminal global access to the TypeScript compiler, simply with using the tsc command.

Here’s a simple example. Open up a code editor of your choice and create a simple file. But, give it an extension of .ts. we will name the file app.ts.

// app.ts
let x: number = 10;
let y: number = 20;
console.log(x + y);

This is a trivial program, only defining two variables and logging their sum. We’re telling the TypeScript compiler to view these variables as numbers. Now when you jump back to the terminal you can compile a JavaScript file from the app.ts TypeScript file.

$ tsc app.ts

Running the command will create an app.js file in the same directory. Opening it up we can see it’s basic ES5 JavaScript.

// app.js
var x = 10;
var y = 20;
console.log(x + y);

What if we assign a string value to a : number variable?

let x: number = 'Hello World!';

Change the value of x to 'Hello World!' and run the tsc app.ts command once again. You’ll get a nice error logged back to you.

app.ts:1:5 - error TS2322: Type '"Hello World!"' is not assignable to type 'number'.

1 let x: number = 'Hello World!';
      ~

We really only want to run the compiled JavaSCript files in a production environment.  For the development environment, we want to use a TypeScript execution environment for Node.js call ts-node

Installing it is as simple as installing TypeScript.

$ npm install -g ts-node

Simple enough. That’s all we need regarding the actual compilers and environments. We’re ready to write some real code.

Real Coding

Let’s get coding, but before we do let us install a few dependencies, express

$ npm install --save express @types/express body-parser

We’re installing express, the express data types for TypeScript, and of course body-parser.

Setting up the compilation pipeline

With the tsconfig.json file, we tell TypeScript what we want to compile and how, as well as where to place the compiled files.

{
  "compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "node",
    "pretty": true,
    "sourceMap": true,
    "target": "es6",
    "outDir": "./dist",
    "baseUrl": "./lib"
  },
  "include": [
    "lib/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

The outDir is set to ./dist, meaning it will create the dist directory and place the compiled files there.

Now when you run the tsc command, it will read this file and compile everything just as you want. Let’s try it.

$ tsc

Running this you’ll see the new dist directory get created along with the app.js and server.js file.  The .js files are now basic JavaScript files, written in ES6.

To make it easier to run, let’s add some scripts in the package.json.  Use “npm init” to create package.json

Open up the package.json. You should have a "scripts" section. Add code so it looks like this:

"scripts": {
  "build": "tsc",
  "dev": "ts-node ./lib/server.ts",
  "start": "node ./dist/server.js",
  "prod": "npm run build && npm start"
},

When you run npm run dev in the terminal you will spin up the app with the ts-node module, but if you run the npm run prod command you’ll first build the TypeScript files, and then run the compiled server.js file from the dist folder.

That’s enough for this article, next we will be looking at how to debug the node.js file that have been generated by TypeScript.

The source can be found here:

https://github.com/BryanAvery/Typescript-with-Node.js

This article could not have been put together without the help of Adnan Rahic and his crash course on TypeScript with Node.js