Introduction

Node is a run-time environment that makes it possible to write server-side JavaScript. It has gained widespread adoption since its release in 2011. Writing server-side JavaScript can be challenging as a codebase grows due to the nature of the JavaScript language; dynamic and weak typed.

Developers coming to JavaScript from other languages often complain about its lack of strong static typing, but this is where TypeScript comes into the picture, to bridge this gap.

TypeScript is a typed (optional) super-set of JavaScript that can help with building and managing large-scale JavaScript projects. It can be thought of as JavaScript with additional features like strong static typing, compilation, and object oriented programming.

Note: TypeScript is technically a super-set of JavaScript, which means that all JavaScript code is valid TypeScript code.

Here are some benefits of using TypeScript:

  1. Optional static typing.
  2. Type inference.
  3. Ability to use Interfaces.

In this tutorial you will set up a Node project with TypeScript. You will build an Express application using TypeScript and transpile it down to neat and reliable JavaScript code.

Prerequisites

Before you begin this guide, you will need Node.js installed on your machine. You can accomplish this by following the How to Install Node.js and Create a Local Development Environment guide for your operating system.

Step 1 — Initializing an npm Project

To get started, create a new folder named node_project and move into that directory.

  • mkdir node_project
  • cd node_project

Next, initialize it as an npm project:

  • npm init

After running npm init, you will need to supply npm with information about your project. If you’d rather let npm assume sensible defaults, then you can add the y flag to skip the prompts for additional information:

  • npm init -y

Now that your project space is set up, you are ready to move on to install the necessary dependencies.

Step 2 — Installing Dependencies

With a bare npm project initialized, the next step is to install the dependencies that are required to run TypeScript.

Run the following commands from your project directory to install the dependencies:

  • npm install -D typescript@3.3.3
  • npm install -D tslint@5.12.1

The -D flag is the shortcut for: --save-dev. You can learn more about this flag in the npmjs documentation.

Now, it is time to install the Express framework:

  • npm install -S express@4.16.4
  • npm install -D @types/express@4.16.1

The second command installs the Express types for TypeScript support. Types in TypeScript are files, normally with an extension of .d.ts. The files are used to provide type information about an API, in this case the Express framework.

This package is required because TypeScript and Express are independent packages. Without the @types/express package, there is no way for TypeScript to know about the types of Express classes.

Step 3 — Configuring TypeScript

In this section, you will setup TypeScript and configure linting for TypeScript. TypeScript uses a file called tsconfig.json to configure the compiler options for a project. Create a tsconfig.json file in the root of the project directory and paste in the following snippet:

tsconfig.json
{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist"
  },
  "lib": ["es2015"]
}

Let’s go over some of the keys in the JSON snippet above:

  • module: Specifies the module code generation method. Node uses commonjs.
  • target: Specifies the output language level.
  • moduleResolution: This helps the compiler figure out what an import refers to. The value node mimics the Node module resolution mechanism.
  • outDir: This is the location to output .js files after transpilation. In this tutorial you will save it as dist.

An alternative to manually creating and populating the tsconfig.json file is by running the following command:

  • tsc --init

This command will generate a nicely commented tsconfig.json file.

To learn more about the key value options available, the official TypeScript documentation offers explanations of every option.

Now you can configure TypeScript linting for the project. In a terminal running in the root of your project’s directory, which this tutorial established as node_project, run the following command to generate a tslint.json file:

  • ./node_modules/.bin/tslint --init

Open the newly generated tslint.json file and add the no-console rule accordingly:

tslint.json
{
  "defaultSeverity": "error",
  "extends": ["tslint:recommended"],
  "jsRules": {},
  "rules": {
    "no-console": false
  },
  "rulesDirectory": []
}

By default, the TypeScript linter prevents the use of debugging using console statements, hence the need to explicitly tell the linter to revoke the default no-console rule.

Step 4 — Updating the package.json File

At this point in the tutorial, you can either run functions in the terminal individually, or create an npm script to run them.

In this step you will make a start script that will compile and transpile the TypeScript code, and then runs the resulting .js application.

Open the package.json file and update it accordingly:

package.json
{
  "name": "node-with-ts",
  "version": "1.0.0",
  "description": "",
  "main": "dist/app.js",
  "scripts": {
    "start": "tsc && node dist/app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/express": "^4.16.1",
    "tslint": "^5.12.1",
    "typescript": "^3.3.3"
  },
  "dependencies": {
    "express": "^4.16.4"
  }
}

In the snippet above, you updated the main path and added the start command to the scripts section. When looking at the start command, you’ll see that first the tsc command is run, and then the node command. This will compile and then run the generated output with node.

The tsc command tells TypeScript to compile the application and place the generated .js output in the specified outDir directory as it is set in the tsconfig.json file.

Step 5 — Creating and Running a Basic Express Server

Now that TypeScript and its linter are configured, it is time to build a Node Express Server.

First, create a src folder in the root of your project directory:

  • mkdir src

Then create a file named app.ts within it:

  • touch src/app.ts

At this point, the folder structure should look like this:

├── node_modules/
├── src/
  ├── app.ts
├── package-lock.json
├── package.json
├── tsconfig.json
├── tslint.json

Open up the app.ts file with a text editor of your choice and paste in the following code snippet:

src/app.ts
import express from 'express';

const app = express();
const port = 3000;
app.get('/', (req, res) => {
  res.send('The sedulous hyena ate the antelope!');
});
app.listen(port, err => {
  if (err) {
    return console.error(err);
  }
  return console.log(`server is listening on ${port}`);
});

The code above creates Node Server that listens on the port 3000 for requests. Run the app using the following command:

  • npm start

If it runs successfully, a message will be logged to the terminal:

Output
  • server is listening on 3000

Now, you can visit http://localhost:3000 in your browser and you should see the message:

Output
  • The sedulous hyena ate the antelope!

Browser window with the message: The sedulous hyena ate the antelope!

Open the dist/app.js file and you will find the transpiled version of the TypeScript code:

dist/app.js
"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const app = express_1.default();
const port = 3000;
app.get('/', (req, res) => {
    res.send('The sedulous hyena ate the antelope!');
});
app.listen(port, err => {
    if (err) {
        return console.error(err);
    }
    return console.log(`server is listening on ${port}`);
});

//# sourceMappingURL=app.js.map

At this point you have successfully set up your Node project to use TypeScript.

Conclusion

In this tutorial, you learned about why TypeScript is useful for writing reliable JavaScript code. You also learned about some of benefits to working with TypeScript.

Finally, you set up a Node project using the Express framework, but compiled and ran the project using TypeScript.

Creative Commons License