Tutorial

How To Set Up a New TypeScript Project

TypeScript

Introduction

You may have worked with TypeScript before when using a starter project or a tool like the Angular CLI. In this tutorial, you will learn how to set up a TypeScript project without a starter’s help. You will also learn how compiling works in TypeScript and how to use a linter with your TypeScript project.

Prerequisites

To complete this tutorial, you will need the following:

Step 1 — Starting the TypeScript Project

To begin your TypeScript project, you will need to create a directory for your project:

  • mkdir typescript-project

Now change into your project directory:

  • cd typescript-project

With your project directory set up, you can install TypeScript:

  • npm i typescript --save-dev

It is important to include the --save-dev flag because it saves TypeScript as a development dependency. This means that TypeScript is absolutely required for the development of your project.

With TypeScript installed, you can initialize your TypeScript project by using the following command:

  • npx tsc --init

npm also includes a tool called npx, which will run executable packages. npx allows us to run packages without having to install them globally. You can learn more about how npx works and when to use it here.

The tsc command is used here because it is the built-in TypeScript compiler. When you write code in TypeScript, running tsc will transform or compile your code into JavaScript.

Using the --init flag in the above command will initialize your project by creating a tsconfig.json file in your typescript-project project directory. This tsconfig.json file will allow you to configure further and customize how TypeScript and the tsc compiler interact. You can remove, add, and change configurations in this file to best meet your needs.

Open tsconfig.json in your code editor of choice, and you will see the following default configurations:

typescript-project/tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true
  }
}

Many of the default configurations will be commented out. The above configurations sets the version of JavaScript your TypeScript will be compiled into and the expected module system for your compiled program. Setting "strict" to true ensures that a wide range of type-checking rules will be enabled. This means your TypeScript program will have fewer errors.

You can customize your TypeScript configuration. In the tsconfig.json file, add the following key-value pairs:

typescript-project/tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "outDir": "dist",
    "sourceMap": true
  }
}

Giving "outDir" the value of "dist" will create a folder or directory called dist. When you run npx tsc to compile your TypeScript file, the compiled JavaScript file will be placed in the dist file.

A sourcemap will also be created when you compile your TypeScript file. A sourcemap is a file that maps the new compiled JavaScript file to the original TypeScript file. When there are errors in your code or if there are changes that need to be made, it is best to debug the original source code rather than the compiled code. This is why sourcemaps are helpful. Setting "sourceMap" to true will allow you to quickly solve errors in the original TypeScript file.

With TypeScript installed and your tsconfig.json file in place, you can now move on to coding your TypeScript app and compiling it.

Step 2 — Compiling the TypeScript Project

Before you can begin coding your TypeScript project, create a folder within typescript-project called src. Inside of the src folder, create an index.ts file.

Open index.ts in your code editor. Write the following TypeScript code in index.ts:

typescript-project/src/index.ts
const world = 'world';

export function hello(word: string = world): string {
  return `Hello ${world}! `;
}

With this TypeScript code in place, index.ts is ready to be compiled:

  • npx tsc index.ts

You will notice that the compiled JavaScript index.js file and the index.js.map sourcemap file have both been added to the dist folder.

Open index.js and you will see the following compiled JavaScript code:

typescript-project/dist/index.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var world = 'world';
function hello(word) {
    if (word === void 0) { word = world; }
    return "Hello " + world + "! ";
}
exports.hello = hello;
//# sourceMappingURL=index.js.map

Running the TypeScript compiler every time you make a change can be tedious. To fix this, you can put the compiler in watch mode. Setting the compiler to watch mode means that your TypeScript file will be recompiled every time changes are made.

You can activate watch mode using the following command:

  • npx tsc -w

You’ve learned how the TypeScript compiler works, and you are now able to successfully compile your TypeScript files. You can take your TypeScript projects to the next level by introducing a linter into your workflow.

Step 3 — Configuring TSLint for the TypeScript Project

Using a linter when coding will help you to quickly find inconsistencies, syntax errors, and omissions in your code. The de facto linter for TypeScript is TSLint.

Warning: TSLint is now deprecated. It is best practice to use ESLint instead. Read this article to learn how to do that: How To Lint and Format Code with ESLint in Visual Studio Code.

To install TSLint, run the following command:

  • npm i tslint --save-dev

TSLint is now installed. To configure TSLint and customize how it works with your project, run the following command to initialize TSLint:

  • npx tslint --init

Initializing TSLint will create a tslint.json file. All of the TSLint configurations are held in tslint.json. Open tslint.json in your code editor. You will see the following default configurations:

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

Linters underline errors in your code. For this behavior to be enabled in your code editor, you will need to install the TSLint extension.

Note: Remember, TSLint is deprecated. Installing TSLint in your code editor may not work.

Return to index.ts in your code editor. You’ll notice underlining in two places: single quotes should be double quotes, and the file should end with a new line. Both of these flagged messages are not errors. They are stylistic preferences that TSLint configures for you. With tslint.json in place, you can change these configurations.

To change these stylistic preferences, you will be working with the "rules" key-value pair in tslint.json:

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

You may not want to include an extra line at the end of every file. You can change this with the "eofline" rule. Setting the value of "eofline" to false will remove the TSLint underlining:

typescript-project/tslint.json
"rules": {
  "eofline": false
},

You don’t have to manually set every rule you would like to add or customize. There are well-known configurations that you can adopt and integrate into TSLint. The Airbnb style guide is one set of configurations that many developers trust and use.

To use the Airbnb style guide, you will first need to install it:

  • npm install tslint-config-airbnb

With the Airbnb style guide installed, you will need to make sure your TSLint configurations in tslint.json reflect this. The "extends" key will need to point to the newly installed tslint-config-airbnb:

tslint.json
{
    "defaultSeverity": "error",
    "extends": "tslint-config-airbnb",
    "jsRules": {},
    "rules": {
        "eofline": false
    },
    "rulesDirectory": []
}

With the Airbnb style guide in place and integrated into tslint.json, TSLint will no longer raise an error message for the use of single quotes. Google also has a widely used TypeScript style guide called gts, which has even more helpful features.

Step 4 — Using gts

You know how TypeScript configuration and linting works. With this behind-the-scenes knowledge, you can use other tools to avoid having to set up linting and configuration in the tsconfig.json file. Google TypeScript Style is one such tool. Google TypeScript Style, known as gts, is a style guide, linter, and automatic code corrector all in one. Using gts will help you to quickly bootstrap a new TypeScript project and avoid bikeshedding. gts also offers opinionated default configuration. This means that you won’t have to do much configuration customization.

To test out gts, begin by creating a new project folder. Once your project folder is in place, initialize gts using the following command:

  • npx gts init

The above command will generate everything you need to get started with your TypeScript, including a tsconfig.json file and a linting setup. A package.json file will also be generated if you don’t have one in place already.

Running npx gts init will also add helpful npm scripts to your package.json file. For example, you can now run npm run compile to compile your TypeScript project. To check for linting errors, you can now run npm run check.

Note: Remember, TSLint is deprecated. Check gts documentation to find out how to integrate gts with the ESLint linter.

To use TSLint with your TypeScript project, you will still need to install TSLint and run npx tslint --init to create a tslint.json configuration file. In the previous step, we extended TSLint to use the Airbnb style guide. You will need to do the same for gts:

tslint.json
{
  "defaultSeverity": "error",
  "extends": [
    "./node_modules/gts/tslint.json"
  ],
  "jsRules": {},
  "rules": {},
  "rulesDirectory": []
}

Now TSLint will follow the linting rules set out by gts.

gts is now installed and properly integrated into your TypeScript project. Using gts on future projects will allow you to quickly set up new TypeScript projects with the necessary configurations in place.

Conclusion

In this tutorial, you began a TypeScript project with customized configurations. You also integrated the Google TypeScript Styleguide into your TypeScript project. Using gts will help you to quickly get up and running with a new TypeScript project. With gts, you won’t need to manually set up configuration or integrate a linter into your workflow.

As an additional step, you might be interested in learning how to work with TypeScript in Visual Studio Code.
You can also check out this article to learn how to use TypeScript with React.

Creative Commons License