Dev Environment to Learn TypeScript

TypeScript is basically JavaScript with types. When writing your code you must define the types of your variables and optionally the returns of the functions. If you have been working with Java or C++ these concepts will feel very familiar.

However there is a small problem, TypeScript is not JavaScript – thus you need to use a compiler to convert your code into JavaScript.

This guide will take a look at how to set up a simple developer environment in order to play around with TypeScript.

Tools needed:

  • NodeJS 11 (It does not matter if you are using the LTS Version or the current Version)
  • VSCode

New Project

In order to create your first project you have to create a directory and initialize it with npm. You can use the Command Line and enter following:

mkdir learn-typescript
cd learn-typescript
npm init -y
code . 

When VSCode is open you can open a Terminal using Ctrl-`

TypeScript

Initial Setup

npm install typescript

this will install the typescript compiler (tsc) to your project. You then could run commands like tsc index.ts and it will compile it to index.js. Which you could execute with node index.js.

However you cannot directly debug your code and it is annoying to run the compile before execution.

Add TS-Node

TS-Node is a tool that allows you to directly execute TypeScript code. It uses the existing tsconfig.jsonto process the code.

npm install ts-node

now you could run the code directly via a command like:

ts-node index.ts

Configure VSCode Debugging Tools

Ts-Node also allows you to use the VSCode debugging tools.

Press Ctrl-Shift-P and enter “Debug: Open launch.json” (this will create a launch.json) Select “Node.JS”

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch current file w/ ts-node",
      "protocol": "inspector",
      "args": [
        "${relativeFile}"
      ],
      "cwd": "${workspaceRoot}",
      "runtimeArgs": [
        "-r",
        "ts-node/register"
      ],
      "internalConsoleOptions": "openOnSessionStart"
    }
  ]
}

Now when you press F5 you can run and debug your typescript code. This also allows you to set breakpoints in VSCode.

Your first “Hello World”

Now create a new file called index.ts and add following code:

async function greeter(name: string): Promise<void> {
  await console.log(`Hello ${name}`)
}

greeter("World");

This “Hello World” takes advantages of Modern ES2017 Features “async/await” as well as adding types for TypeScript.

When you press F5 in VSCode this should result in an error as Promises are not available in ES5. We can fix this by configuring the compiler.

Configuring the compiler

In order to configure the compiler you need to run the command:

tsc --init

this will create a tsconfig.json file. with this file you can configure the compiler. When creating it with the command it creates the file with the defaults and comments on what each compiler flag does.

One of the settings you should adjust is the “target” attribute. Currently it defaults to “es5” – this is because Internet Explorer 11 only supports ECMAScript 5.

We are targeting with our code NodeJS 10+, so we can change this value to “es2017”. As you can determine from this table

Running Hello World again

Now press F5 again the output should show you “Hello World”.

Conclusion

Now you are set to experiment some more with TypeScript.

One of the things you can experiment with is changing the target version of the compiler and running tsc index.ts and take a look at the resulting JavaScript code. You will see that compiling to es5 or es6 the compiler adds a lot of extra code to enable functioning code, however when compiling to es2017 it (almost) only strips away the types and leaves the code practically identical.

Attachments:

Compiling the code to ES5

To fix the code to compile to ES5 we first need core-js a library that provides polyfills for older versions of JavaScript.

npm install core-js @types/core-js

now we must add the line index.ts:

import 'core-js/es6/promise';

async function greeter(name: string): Promise<void> {
  await console.log(`Hello ${name}`)
}

greeter("World");

and in our tsconfig.json: we must add:

"lib": [
      "es2015",
      "dom"
    ],

Now your code should compile and run on IE11.

Visual Studio Code Extensions (September 2018)

Lets take a look at a couple of very useful Visual Studio Code Extensions.

General

Settings Sync

The tool allows you to synchronize your settings on multiple computers and/or operating systems. You need to have a github account and it will create a secret gist in order to sync your settings. Read More

Settings Sync

Code Runner

Basically it adds a small play button at the top of every file and lets you immediately execute it.

Code Runner

Git Lens

Git Lens dramatically enhances the GIT experience in VSCode. Inline display of code authorship, easy comparison with previous versions of the file and many more features.

Git Lens

Code Quality

TODO Highlighter

It highlights your comments that start with \\ TODO: or \\ FIXME:. Additionally it adds a command to list all Todos in your source code so you can identify and complete / fix the code.

If you use a different convention in your codebase you can configure the plugin to fit your use case.

TODO Highlighter

Spell Checker

Basically this complains when you start creating variable names that have no meaning. While ensuring that your documentation does not contain any spelling mistakes.

You can add words to a project dictionary And it is easily expandable to support additional languages.

Spell Checker

TSLint

It uses the local tslint.json and integrates the information into VSCode. You can enable ‘tslint.autoFixOnSave’ that automatically applies the defined rules (that can be autofixed).

TSLint

Theme

Cobalt2

A great dark theme with high contrast color choices. Personally I do not follow the official documentation on how to set up the theme. (Too many steps and it requires the font Operator Mono that costs 200USD )

Cobalt2 Theme Official

VS Code Great Icons

Well better Icons for VS Code

Great Icons

Image: Designed by Freepik

VSCode: Launch create-react-app and Chrome with launch.json

Developing React (with create-react-app) and Visual Studio Code you usually press ESC-` and then npm start. The script from create-react-app then automatically starts a Browser. That you then close. then reopen by pressing F5 to start Chrome in debug mode.

Let’s make these steps a little quicker.

Create a Task for npm start

Press Ctrl-Shift- and Select “Tasks: Configure Default Test Task” This will create a tasks.json file.

In the tasks.json file you need to add a couple of values:

  • isBackground: true – launch.json will not wait until the task completes
  • problemMatcher Needs to be defined to figure out when the task has completed its initialization phase and it is safe to continue with the next task
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "type": "npm",
            "script": "start",
            "group": {
                "kind": "test",
                "isDefault": true
            },
            "isBackground": true,                       //This prevents the launch.json to wait for the completion of the task
            "problemMatcher": {
                "owner": "custom",                      //This is not needed but, required by the problemMatcher Object
                "pattern": {
                    "regexp": "^$"                      //This is not needed but, required by the problemMatcher Object
                },
                "background": {
                    "activeOnStart": true,
                    "beginsPattern": "Compiling...",    //Signals the begin of the Task
                    "endsPattern": "Compiled .*"        //Signals that now the initialization of the task is complete
                }
            },
            "identifier": "Start Server"
        }
    ]
}

Configure create-react-app

To prevent launching the browser you need to add in your .env-file following line:

BROWSER=none

More Info:

Configure the Launch.json file

Press F5 and select Chrome and a launch.json file will be created.

  • Change the port to 3000 (create-react-app default)
  • Add a preLaunchTask to start the task we defined earlier
{
    "version": "0.2.0",
    "configurations": \[ 
        {
            "name": "Chrome",
            "type": "chrome",
            "request": "launch",
            "url": "http://localhost:3000",         //Change to the create-react-app default 3000
            "webRoot": "${workspaceRoot}/src",
            "preLaunchTask": "npm: start"           //Add prelaunch Task npm: start (defined in tasks.json)
        }
    \]
}

Start Working

Tadaa, now you press F5 and can start debugging directly in vscode. The background task will continue running even when you stop debugging.

Stop Working

You need to terminate the task via ctrl-shift-p > terminate Task. (Or you just close vscode)