TypeScript Fundamentals

TypeScript Fundamentals

This is a not tutorial, but just my learning note of TypeScript. This blog will not tell the reasons for why we are doing this. However, you can still follow this blog to make things work. 

I spend less than a day to write this blog since I learned TypeScript before. The purpose of this note is to help me remind the knowledge I learned and training my teammates for a team project. If there are any mistakes out there, pls point them put in the comment area, thank you.

1. Installation

npm install -g typescript

 

Test if you installed successfully, by typing the following code into your terminal

tsc --version

Now try to make your first Typescript program:

mkdir ts-hello
cd ts-hello

create a new file called main.ts

function log(message){
        console.log(message);
}
        
var message = "hello world";
log(message);

After you saved the file, we need to compile the TypeScript code into javascript.

tsc main.ts

tsc stands for TypeScript Compiler.

Now you can see main.js in the same folder. The content of .ts and .js file is basically same.

Then, run the main.js by typing

npm main.js

Now you should see hello world on the terminal.

2. Declaring variables

function doSth(){
        for (var i = 0; i < 5; i++){
                console.log(i);
        }
        console.log("final" + i);
}       
doSth()
        
0
1
2
3
4
final5

See the 5 after final? Because if we use “var”, the variable we declare inside the for block will still exist outside the for block.

Use “let” keyword, the compiler will fail to compile. It will be just like java, only be able to be accessible inside the for block.

Since we are using TypeScript here, we are going to use “let” keyword to declare variables at any time.

3.Types

let count = 5; // count is a number 
count = 'a' // Here will be a compiling error 

let a; // the type of a is any;

let a:number; // by using : we can declare the type

let b: boolean;
let c: string;
let d: any;
let e: number[];
let f: any[]

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

enum Color {Red, Green, Blue};
let bgColor = Color.Red;

Type assertions

let msg; // type any
msg = 'abc';
let endWithC = (<string>msg).endsWith('c'); // method #1;
let method2 = (msg as string).endsWith('c');

4.Arrow function

The arrow function of typeScript is just like the lambda function in Java and C#. Let me give you an example.

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

let arrow = (msg) => console.log(msg);
// if you only have one parameter, you can get rid of the ()

 5. Interface

The concept of the interface of the typescript is as the same as the in java.

  • no implementation of methods
let drawPoint = (point) => {
    //... it expecting x: number and y: number
}

// However, you can still pass anything into that function without compiling errors
// that are going to make our program easily being crushed, for example, pass in point object without 
// field x and y will crush our program

drawPoint({
    x: 1;
    y: 2
})

interface Point {
    x: number,
    y: number
}
// we defined our interface, and we change our function into this

let drawPoint = (point: Point) => {
    //... it expecting x: number and y: number
}

// problem solved

6. Classes

The concept and implementation is similar to in java

class Point {
    x: number;
    y: number;

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

7. Object

Object is simple as well, continue with the example above.

class Point {
    x: number;
    y: number;

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

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

8. Constructor

using the signature constructor to announce it.

if you want the parameter to be optional, put a question mark after it.

Every parameter after the parameter that you set optional have to be optional 

class Point {
    x: number;
    y: number;

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

    //if you want to make the parameter optional, put a question mark after it. 
    constructor(x?: number, y?: number){
        this.x = x;
        this.y = y;
    }

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

let point = new Point();
point.draw();

9. Access Modifier

Just like Java, we have Access Modifier

  • public
  • private
  • protected
class Point {
    private x: number;
    private y: number;

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

    //if you want to make the parameter optional, put a question mark after it. 
    constructor(x?: number, y?: number){
        this.x = x;
        this.y = y;
    }

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

let point = new Point();
point.draw();

By adding private before x and y, you can no longer access them out of the class.

Access Modifier in Constructor Parameters

Let me explain it a little bit, we can declare our fields in the constructor by using access modifiers.

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

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

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

let point = new Point();
point.draw();

10. Properties

Using “get” and “set”, x is now a property of the class point,  we can access x just as a filed. However, by the code in set x(val), we constrain the value that user possibly passing in.

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

    get X(){
      return this.x;
    }
    
    set X(val){
      if (val < 0){
          throw new Error('value cannot be less than 0');
      }
      this,x = val;
    }

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

let point = new Point();
point.draw();

11. Modules

We need a better way to organize the structure of our code, so we separate our code into different files.

let s create a new file called “point.ts” and put the code of point class into it.

And we add “export” before the class, so other files can access this class.

//point.ts
export class Point {
    constructor(private x?: number, private y?: number){
    }

    get X(){
      return this.x;
    }
    
    set X(val){
      if (val < 0){
          throw new Error('value cannot be less than 0');
      }
      this,x = val;
    }

    draw(){
        console.log('X: '+this.x+', Y: '+this.y);
}
//main.ts
import { Point } from './point';

let point = new Point();
point.draw();

 

Leave a Reply

Your email address will not be published. Required fields are marked *