TypeScript by Example

TypeScript by Example

A Quick Reference

Introduction

This intends to be a quick reference for an experienced developer to quickly learn and use Typescript.

Commands

Install on the local machine Typescript engine

npm install -g typescript

Check version

tsc --version

Transpile Typescript to Javascript

tsc <file>

Variables

Declaring, Assign and Types

var - variable scope is global;

let - variable scope is constricted to the place where is created;

The next example shows how to declare a variable with a type and assign a value:

let a: number = 10;
let b: boolean = true;
let e: number[] = [1,2,3];
let f: any[] = [1, true, 'a', false];

Enums

It's good practice, to create the enum and assign a value to it

enum Color {Red = 0, Green = 1, Blue = 2, Purple = 3};

let backgroundColor = Color.Red

Type Assertions

Type Assertion is a way to inform the TypeScript compiler of the data type of a variable. It does not change a variable's data type.

let message; //type any
message = '123' //assigned a string
let assert1 = (<string>message).endsWith('3'); // (<string>message) more common 
let assert2 = (message as string).endsWith('3);

Arrow Function

Look at the next function in plain Javascript:

let log = function(message){
    console.log(message);
}

The same Function can be expressed in Typescript as a Arrow Function. An Arrow Function is the same as a Lambda Expression in Java

let log = (message) => {
    console.log(message);
}

The same but more compact:

let log = (message) => console.log(message);

Objects, Interfaces and Classes

Interfaces

Declaring the Point Interface

interface Point {
    x: number,
    y: number
}

Using the Point interface in a function argument:

let drawPoint = (point: Point) =>{
    // ...
}

Classes

Class Point with x and y properties and draw() and getDistance(another: Point) functions


class Point{
    x: number;
    y: number;

    draw(){
        console.log('X: ' + this.x + ', Y: ' + this.y);
    }

    getDistance(another: Point){
        // ...
    }
}

Objects

Instantiating an Object and using it

//create variables and assign object
let point = new Point()

//Assign values to point variables
point.x = 1;
point.y = 2;

//run function of point
point.draw();

Output: X: 1, Y: 2

Object Constructor

In TypesScript, an Object Constructor is created with the keyword constructor.


class Point{
    x: number;
    y: number;

    constructor(x: number, y:number){
        this.x = x;
        this.y = y;
    }

    draw(){
        console.log('X: ' + this.x + ', Y: ' + this.y);
    }

}

let point = new Point(1, 2);
point.draw()

A class in Typescript can only have one constructor, to have the possibility of multiple argument combinations on instantiation, it is necessary to add the ? to the constructor argument to make it optional.

Class with constructor and optional arguments:


class Point{
    x: number;
    y: number;

    constructor(x?: number, y?:number){
        this.x = x;
        this.y = y;
    }

    draw(){
        console.log('X: ' + this.x + ', Y: ' + this.y);
    }

}


let point = new Point();

Access modifiers

In Typescript allowed access modifiers are public, private and protected. By default, if no access modifier is not defined it is public.


class Point{
    //private arguments
    private x: number;
    private y: number;

    constructor(x?: number, y?:number){
        this.x = x;
        this.y = y;
    }

    //no access modifier then it is public
    draw(){
        console.log('X: ' + this.x + ', Y: ' + this.y);
    }

}


let point = new Point();

Access Modifiers in Constructor Parameters

In this example, there is no need to specify the variables in the body's class. The transpiler will create them automatically. It is the same as the previous example.


class Point{

    constructor(private x?: number, private y?: number){
    }

    draw(){
        console.log('X: ' + this.x + ', Y: ' + this.y);
    }

}

But with a class like this, 'x' and 'y' cannot be accessed from outside, because they are private.

So we create fields _x and _y and their corresponding setter and getter properties.


class Point{

    constructor(private _x?: number, private _y?: number){
    }

    draw(){
        console.log('X: ' + this._x + ', Y: ' + this._y);
    }

    //x property getter
    get x(){
        return this._x;
    }

    //x property setter
    set x(value: number){
        if(value < 0)
            throw new Error('value cannot be less than 0.');
    }
}

Usage:

let point = new Point(1,2);
let x = point.x; //point.x is using get x()
console.log("x is: " + x);
point.x = 10; //point.x is using set x (value:number)
point.draw();

Output:

x is: 1
X: 10, Y: 2

Modules

A Module is a file where the code resides. To make a class available to outside modules just add the 'export' keyword.

export class Point{

    constructor(private _x?: number, private _y?: number){
    }

    draw(){
        console.log('X: ' + this._x + ', Y: ' + this._y);
    }
}

in the file where you want to use Point class, use an import statement:

//    class to use     path to the file where class resides
import { Point } from './point';

Check the module folder for a working example.