TypeScript

Hello World

write a simple javascript and save it as main.ts

function log (message){
    console.log(message);
}
var message = 'Hello World';
log(message);
1
2
3
4
5

Compile it using typescript compiler

tsc main.ts
1

run js file using node

node main.js
1

Types of Variables

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

const ColorRed = 0;
const ColorGreen = 1;
const ColorBlue = 2;

enum Color {Red = 0, Green = 1, Blue = 2, Purple = 3 };
let backgroundColor = Color.Red;
1
2
3
4
5
6
7
8
9
10
11
12
13

Type Assesions

Give the variable a type so Autocomplete can recongnise

let message;
message = 'abc';
let endsWithC = <string>message.endsWith('C');
let alternativeWay = (message as string).endsWith('C');
1
2
3
4

Arrow Functions

Equal to Lamda Expression in C#

let log = function(message)
{
    console.log(message);
}
//arrow function
let dolog = (message) => console.log(message);
let dolog1 = () => console.log("test");
1
2
3
4
5
6
7

Interfaces

interface Point {
    x: number, //use commana instead of semi colon
    y: number,
    draw: () => void // add function decoration here
}
let drawPoint = (point: Point) => {

}
drawPoint({
    x: 1,
    y: 2
})
1
2
3
4
5
6
7
8
9
10
11
12

Classes

class Point{
    x: number;
    y: number;

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

    draw (){
        // ...
    }
    getDistance(another:Point){
        // ...
    }
}
let Point = new Point();
point.draw();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

In typeScript cannot have multiple constructor, can only add ? (Which means Optional)

Access Modifiers

Add access Modifiers so the class parameters cannot be accessed

class Point{
    private x: number;
    private y: number;
    //...
}
1
2
3
4
5

or

class Point{
    constructor(private x?:number, private y?:number){
    }
    //...
}
1
2
3
4
5

Properties

same as getter and setter

class Point{
    constructor(private _x?:number, private _y?:number){
    }
    get x(){
        return this._x;
    }
    set x(value){
        if(value < 0)
            throw new Error('value cannot be less than 0');
        this._x = value;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12

Modules

in order to seperate class to diffferent files, the class being called should be exported and the class that use the class should be
main.ts

import { Point } from './point'; // import in main
let point  = new Point();
point.draw();
1
2
3

point.ts

export class Point{  // export the class so other class can call
    draw(){
        //...
    }
    //...
}
1
2
3
4
5
6
Last Updated: 1/14/2019, 12:15:15 AM