TypeScript

First Steps

Basics Install Typescript Setup Variables and Types


Table of Contents

In this lesson we will setup our project and write our first TypeScript program.

Many editors support TypeScript (some with TypeScript extensions).

Visual Studio Code (VS Code) will be used in this lecture. If using VS Code, TypeScript support is built-in, so there are no extensions required.

Topics on this page:


Installation

The easiest way to install TypeScript is through npm, the Node.js Package Manager. After npm has installed, you can install TypeScript on your machine.

Installing Node.js

Node.js with NPM (Node Package Manager) - npm is the package manager for JavaScript. It hosts almost half a million packages of free, reusable code — the largest software registry in the world. Use npm to install any npm package into your project.

To check whether or not you have Node.js installed, visit your console / command line and type (you can do it straight inside VS Code terminal):

node -v 

If this command goes unrecognized, you need to install Node.js. Go to Node.js, choose either the Windows or Mac installer based on your OS, and download it. By default, it will install the npm package manager which we will need.
After it's installed, close your console / command line and reload it. You can now run the node -v command and it will provide you with the current version number.

Next, we need to insatll TypeScript transpiler to JavaScript.

Installing TypeScript

Look in Compiling TypeScript for more information.

TypeScript can either be installed globally (available anywhere in your file system) or locally (only available at the project level).

For global installation (available anywhere in your file system) type at the console:

npm install -g typescript

To install locally (only available at the project level) type at the console:

npm install --save-dev typescript

To check that TypeScript is installed type:

tsc --version
tsc --help

To check available tsc commands type:

tsc

First Program

Create a new folder for your new project. Open the folder in VS Code or go into that directory while you in Command Shell and then open VS Code at this location by typing:

code .

Open a new TypeScript file. We will call it app.ts (.ts is a must TypeScript file extension). Type in the file:

class Hello {
    constructor(public message: string) {}
}

let hello = new Hello('Hello class, How are you?');
console.log(hello.message);
        

You can see that you get language features such as syntax highlighting and bracket matching. When you were typing in the editor, you may have noticed IntelliSense, the smart code completions and suggestion provided by VS Code and the TypeScript language server.

To compile the code and to get the .js output file type in the console:

tsc app.ts

Notice that app.js file was created. Look at it. Run the code by typing in the console:

node app.js

Visual Studio Code Setup

Make sure you have the following VS Code extensions:

You can modify the TypeScript compiler options by adding a tsconfig.json file which configures the TypeScript project settings such as the compiler options and the files that should be included. The tsconfig.json file should be put in the project's root directory.
To create a TypeScript configuration file, you can run the following command (run it once):

tsc --init

This will create a default tsconfig.json file with some default options set for you and a bunch of other options commented out. Set the options to compile to ES5 and use CommonJS modules. In the following the output of transpiling will be redirected to "out" folder. You can change the folder if you want:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "sourceMap": true,                     /* for debugging */
        "outDir": "out",                       /* Redirect output structure to the directory. */
        "strict": true,                        /* Enable all strict type-checking options. */
        "noUnusedLocals": true,                /* Report errors on unused locals. */
        "noUnusedParameters": true,            /* Report errors on unused parameters. */
        "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
        "esModuleInterop": true ,              
        "noEmitOnError": true                  /* don't generate js file if error exists */
    }
}
        

When tsconfig.json file is present, every compilation will use the options defined in the file. You can compile multiple files by typing:

tsc

And you can also make compilation run on save by doing:

tsc --watch
or
tsc -w

See the official documents in tsconfig.json and Compiler Options.


Compiling TypeScript

Instead of using tsc for transpiling the file, we can automate the process by use of Run Build Task from the Terminal menu (Ctrl+Shift+B).

After tsconfig.json is defined, if you'd like for the TypeScript compiler to watch for changes in your TypeScript files and automatically trigger the transpilation of .ts to .js files, you can use Ctrl+Shift+B to bring up a menu that can run the transpiler in either normal or watch modes (tsc:build or tsc:watch, respectively).

You can also define the TypeScript build task as the default build task so that it is executed directly when triggering Run Build Task (Ctrl+Shift+B). In the top "Terminal" menu choose "Configure Default Build Task". Select tsc: watch which generates the following tasks.json file in .vscode folder:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558 
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "type": "typescript",
            "tsconfig": "tsconfig.json",
            "option": "watch",
            "problemMatcher": [
                "$tsc-watch"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}
        

Press Ctrl+Shift+B and it will start compilation in watch mode by default (will compile on any change of the saved code). Run the program as previously or use the top "Debug" menu (Ctrl+F5 as in Visual Studio).


Debugging

To debug an application in VS Code, press F5 while you in the .ts file and VS Code will try to debug your currently active file. You can set breakpoints to stop on any code line.

In case you already have the launch.json file (see the next section) and you want to run ts code not on the client, you need to add Node.js configuration to the launch.json file (see the next section).


Using TypeScript with HTML

In the folder of your first program create the following hello.html file:

<!DOCTYPE html>     

<html lang="en">

<head>
    <title>Page Template</title>
    <meta charset="utf-8">     
    <script src="out/app.js"></script>     
</head>

<body>
</body>
<html>
        

Run tsc to build the app and then test by opening hello.html in your browser.

To debug the client-side code, install the Debugger for Chrome extension. VS Code keeps debugging configuration information in a launch.json file located in a .vscode folder in your workspace (project root folder).

While you in hello.ts file in the editor, press F5 to generate launch.json file. Choose Chrome. You will get the following launch.js file content:

{
    // 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": "chrome",
            "request": "launch",
            "name": "Launch Chrome against localhost",
            "url": "http://localhost:8080",
            "webRoot": "${workspaceFolder}"
        }
    ]
}
            

Now run in the terminal:

http-server

http-server is a Node package required to setup a web server. See on which port localhost is set and change url accordingly in the launch.json file.

Instead of localhost you can use the location of your file on your computer. To do this, update the launch.json to specify the local file URL to hello.html:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch Chrome against localhost",
            "url": "file:${workspaceFolder}/hello.html,
            "webRoot": "${workspaceFolder}"
        }
    ]
}

Now you can use F5 or Ctrl+F5 to debug/run your application (or through Debug menu).

The full configuration together with Node.js (so you can run ts file not in the client) will look like:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch Chrome against localhost",
            "url": "file:${workspaceFolder}/hello.html,
            "webRoot": "${workspaceFolder}"
        },
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "skipFiles": [
                "/**"
            ],
            "program": "${workspaceFolder}/hello.ts",
            "outFiles": [
                "${workspaceFolder}/out/**/*.js"
        }
    ]
}

You can control what you use (Node.js or Chrome) by pressing the debug icon on the left side of the VS Code window and choosing the required configuration.

For more information see Debugging TypeScript.