Thursday, April 10, 2014

Introduce of TypeScript (Part 1)

Previously I just learn something new to me, TypeScript (acutally it first introduced in 2012).
TypeScript is a superset of JavaScript, it preserve all syntax of JavaScript, and with something new (eg. modules, class, interface). By means of compilation, the TypeScript is compiled into JavaScript which is still quite readable.
Actually the Offical Site aready provide very clean introduction and tutorial about the language. So today I would only talk about the typing concept and modules class interface.
As we know JavaScript is weak typing language.

var a = 0;
var b = "0";
var c = false;
a == b && b == c; // true

So TypeScript want to solve this issue by adding strong typing concept to JavaScript

// explicitly tell TypeScript compiler
// what is the type of variable a,b,c
var a : any = false;
var b : number = 0;
var c : string = "0";

// OK code since "a" is in "any" type
a = c;

// Cause compilation error (error TS2011: Cannot convert 'number' to 'string'.),
// but it still preserve in js file because it is valid JavaScript
b = c;

var a = false;
var b = 0;
var c = "0";

a = c;

b = c;

Actually the type is only use for compilation warning, or for IDE to know, it is so clear and beautiful. To be more advance, you can also declare function parameters type and return type.
function func(arg1: string, arg2: string) : Array<string> {
    return [arg1, arg2];

function func(arg1, arg2) {
    return [arg1, arg2];

No comments:

Post a Comment