Thursday, April 10, 2014

Introduce of TypeScript (Part 2)

Lets continues the topic about TypeScript, I am going to introduce interface, class and module.
Interface
Nothing would change the behavious of JavaScript, but it is good stuff for compiler or IDE to perform type checking. Let's see the example.
interface IVector2D {
    x : number;
    y : number;
}

var a : IVector2D = {x:0, y:0}; // Valid
var b : IVector2D = {x:1, y:1, z:1}; // Valid, fulfill the interface
var c : IVector2D = {x:2}; // Compile error, missing number "y"

var a = { x: 0, y: 0 };
var b = { x: 1, y: 1, z: 1 };
var c = { x: 2 };

With the interface, you are more safe to write some advance function, since compiler or IDE warn you when the type is missmatch. Such as the following example.
function addVector2D (v1 : IVector2D, v2 : IVector2D) : IVector2D {
    return {
        x : v1.x + v2.x,
        y : v1.y + v2.y
    };
}
var d = addVector2D(a, b); // {x:1, y:1}
var e = addVector2D(0, 1); // Compile error

Class
JavaScript is a kind of prototype-based object oriented programing, which is quite different from class-based OOP. Before the next standard of JavaScript (ECMAScript 6) become popular in all browser, TypeScript is the easiest ways to make Class in JavaScript.
class People {
    name : string; // public attribute
    constructor (name : string){ // class constructor
        this.name = name;
    }
    greet () : string { // public method
        return 'Hi, my name is ' + this.name;
    }
}

// Subclass Staff which extends People,
// implements an interface is also possible
class Staff extends People {
    post : string;
    constructor (name : string, post: string){
        super(name); // must call the superclass constructor
        this.post = post;
    }
    greet() : string {
        return super.greet() + ' I am a ' + this.post;
    }
}
var me = new Staff('KiLla', 'Programmer');
console.log(me.greet()); // Hi, my name is KiLla I am a Programmer

Module
For better manage the code, and prevent polluting the globle scrope, module pattern is always recommended for large scale system / library. With TypeScript, you can ECMAScript 6 compliance code very easily.
module mod {
    export var attr : number = 0; // use the "export" keyword, just like nodejs
    export function func() {
    }
}
module mod.submod {
    export class myclass {
    }
}
var a = mod.attr;
var b = mod.func();
var c = new mod.submod.myclass();

No comments:

Post a Comment