Our first TypeScript code

Before you start:

Make sure that you have installed TypeScript — if you haven't check this lesson first.

Let's write our first line of TypeScript code. Before we will do it let me clarify one thing. TypeScript is independent of Angular, therefore you can use TypeScript without using Angular. Let's see how to do that.

  1. Open a terminal and create a file main.ts:
  2. console.log("Hello TS World");
  3. Now run following command:
  4. tsc main.ts

    This will run TypeScript compiler and compile TypeScript to JavaScript. If you run ls (macOS/unix) or dir (Windows) command. You should see 2 files:

    -rw-r--r--  1 Dawid  staff  31 Feb  1 20:35 main.js
     -rw-r--r--  1 Dawid  staff  31 Feb  1 20:35 main.ts

    Our TypeScript code (main.ts) was compiled to JavaScript (main.js).

  5. Let's run our js code using node:
  6. node main.js

    You should see:

    Hello TS World

    And again step by step:

    TS superset of JS

    That confirms what we I have stated before:

    Any valid JavaScript code is also a valid TypeScript code.

Visual Studio Code

Now you understand that TypeScript is independent of Angular, however, Angular cannot work without TypeScript. Therefore whenever you are running ng serve, or ng build, Angular CLI is calling the TypeScript compiler under the hood, so to compile the code of our application to JavaScript that can be used by browsers.

While working with Angular you will hardly use the tsc command and stand-alone files, therefore we will switch to Visual Studio Code now.

  1. Open Visual Studio Code
  2. Open our recent project /my-app (if you missed that check previous tutorial where we set up our project).
  3. Replace the content of /src/app/app.component.ts file with the following:
  4. import { Component } from '@angular/core';
     
       @Component({
         selector: 'app-root',
         templateUrl: 'app.component.html',
         styleUrls: ['app.component.css']
     
       })
     
       export class AppComponent {
     
         constructor(){
           this.onStartup();
         }
     
       onStartup(){
         console.log('Hello TS World');
       }
       }
  5. Save the file, then run ng serve -o. When the CLI opens a new tab/window with our project, open the developer console. You will see:
  6. Console .log

    As you noticed we have created a function — onStartup() — and added it to the constructor of our AppComponent. Whenever an instance of our component is created, it will call our onStartup function.