Looking for a specific post? Checkout the Blog Index.

By Kimserey Lam with

Getting Started With Typescript

Jul 19th, 2019 - written by Kimserey with .

In previous blog posts we looked into features of Angular. The language used to code Angular is Typescript - a superset of Javascript, and Angular itself relies heavily on the features of Typescript but also NodeJS libraries. When it comes to testing functionalities completely unrelated to the browser or even the website itself, it is good to have an easy way to design a piece of logic with functions, classes, and module and execute it directly using Node rather than having to bundle it within an Angular SPA. With that idea in mind, today we will look into how to setup a simple project running Typescript code which will allow us for example to test functionalities of rxjs without the need to bootstrapping a frontend project.

Setup a Typescript Project

We start by creating a folder for our project:

1
2
mkdir my-typescript-project
cd my-typescript-project

Then within the folder we initiate npm and install locally Typescript, Tslint the linter for Typescript and @types/node. If we look under /node_modules/@types/node/ we will find all type declarations for

1
2
npm init
npm install --save-dev typescript tslint @types/node

As we will be executing our Typescript code in NodeJS, we installed the type definition for NodeJS with @types/node. This allows us to import and use NodeJS libraries in a type safe manner behind clearly defined modules, interfaces and function signatures.

Typescript being a superset of Javascript, it needs to be transpiled to it. For that we need to have a tsconfig.json providing configuration options for the Typescript compiler.

We can automatically initialise the configuration by running:

1
npx tsc --init

npx is used to execute commands from binaries directly under /node_modules/.bin/. The default tsconfig.json contains the properties you specify. A minimal configuration can be:

1
2
3
4
5
6
7
8
9
10
11
12
{
    "compilerOptions": {
        "module": "commonjs",
        "outDir": "dist",
        "sourceMap": true,
        "strict": true,
        "target": "es2015"
    },
    "include": [
        "src"
    ]
}

Where we specify the module code generation used, the target and the files to include. As part of the compiler options, we can restrict certain notations for example we can add

1
"noImplicitAny": true

Which will warn when a type is implicitely inferred as any. There are plenty of other options which will allow us to enforce a similar convention in our codebase.

Lastly just like tsconfig.json, to complete our configuration we create a tslint.json file which allows us to configure the linter settings using the same command:

1
npx tslint --init

This will create the following configuration:

1
2
3
4
5
6
7
8
9
{
    "defaultSeverity": "error",
    "extends": [
        "tslint:recommended"
    ],
    "jsRules": {},
    "rules": {},
    "rulesDirectory": []
}

Which extends the recommended settings for tslint. You can add new rules based on your preferences. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
    "defaultSeverity": "error",
    "extends": [
        "tslint:recommended"
    ],
    "jsRules": {},
    "rules": {
        "semicolon": [true, "always"],
        "trailing-comma": false,
        "no-console": false,
        "arrow-parens": false,
        "interface-name": false,
        "max-classes-per-file": false
    },
    "rulesDirectory": []
}

Compile and Run Typescript

I use Visual Code as IDE, it comes with direct support for Typescript language and has a built-in code formatting with ALT+SHIFT+F.

Now that we are ready to write typescript, we can create a index.ts file under /src/.

1
console.log("Hello World");

Then we can execute the Typescript compiler command:

1
npx tsc

The compiler will use the tsconfig.json and transpile the Typescript code to Javascript while placing it in the /dist/ folder. We can then use NodeJS to execute the Javascript.

1
2
$ node ./dist/index.js
Hello World

To use the linter we can run:

1
npx tslint --config tslint.json --project tsconfig.json

But if you are using Visual Code, you can install Tslint extension which will directly tell you when your code triggered a warning.

Compiling then running the output with NodeJS can be reduced to a single step using ts-node.

1
npm install ts-node

This will install the package locally without saving it as dependency then we can run ts-node directly:

1
2
$ npx ts-node .\src\index.ts
Hello World

Visual Code Debugger

In order to debug with breakpoint Typescript code, we can use Visual Code debugger. We start first by creating a task using CTRL+SHIFT+B. This will prompt us to choose a task to build. As Typescript is supported by default, Visual Code knows that we are trying to build Typescript and we can define [tsc: build - tsconfig.json] or [tsc:watch - tsconfig.json] task. build will compile the code and output it in the /dist/ folder.

To create the task, we click on the setting on the prompt which will create the following tasks.json under /.vscode/:

1
2
3
4
5
6
7
8
9
10
11
12
13
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "type": "typescript",
            "tsconfig": "tsconfig.json",
            "problemMatcher": [
                "$tsc"
            ]
        }
    ]
}

We have named the task build, when we CTRL+SHIFT+B, we will now see build as option.

Then we can create a launch.json file under /.vscode/ which will allow us to run the code with debugger:

1
2
3
4
5
6
7
8
9
10
11
12
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${workspaceFolder}/dist/index.js",
            "preLaunchTask": "tsc: build - tsconfig.json"
        }
    ]
}

PreLaunchTask will run the same task that we specified in the build task. Your folder structure should look as such:

1
2
3
4
5
6
7
8
9
10
11
12
13
.vscode/
  launch.json
  tasks.json
dist/
  ... output files
node_modules/
  .... node modules
src/
  index.ts
package.json
package-lock.json
tsconfig.json
tslint.json

And that concludes today’s post. We will now be able to run and breakpoint inside our Typescript code!

Conclusion

Today we saw how we could bootstrap a Typescript project by setting up the essential compiler and linter configurations. We then saw how we could use Visual Code to code Typescript easily and setup build task and debugger to breakpoint in our Typescript code. I hope you liked this post and I see you on the next one!

Designed, built and maintained by Kimserey Lam.