Types – Classes and Inheritance – Modules



Types – Classes and Inheritance – Modules

0 0


typescript.intro

Quick intro to TypeScript

On Github saintedlama / typescript.intro

TypeScript

Quick Intro

TypeScript is...

  • Open Source
  • Javascript Pre Compiler
  • ES 6 Harmony in 2012

Types

Ambient Declarations

                            
declare var document;
document.title = "Hello";  // Ok because document has been declared
                            
                        

Function Types

                            
function vote(candidate: string, callback: (result: string) => any) {
    // ...
}

vote("BigPig", function(result: string) {
    if (result === "BigPig") {
        // ...
    }
});
                            
                        

Interfaces

                            
interface Point {
    x: number;
    y: number;
}

function getX(p: Point) {
    return p.x;
}

class CPoint {
    constructor (public x: number, public y: number) { }
}

getX(new CPoint(0, 0));  // Ok, fields match
getX({ x: 0, y: 0, color: "red" });  // Extra fields Ok
getX({ x: 0 });  // Error: supplied parameter does not match
                            
                        

Classes and Inheritance

Classes and Inheritance

class BankAccount {
    constructor(public balance: number) {
    }

    deposit(credit: number) {
        this.balance += credit;
        return this.balance;
    }
}

class CheckingAccount extends BankAccount {
    constructor(balance: number) {
        super(balance);
    }

    writeCheck(debit: number) {
        this.balance -= debit;
    }
}


ES Harmony - Classes

class SkinnedMesh extends THREE.Mesh {
    constructor(geometry, materials) {
        super(geometry, materials);

        public identityMatrix = new THREE.Matrix4();
        public bones = [];
        public boneMatrices = [];
        ...
    }

    update(camera) {
        ...
        super.update();
    }
}


See ES Harmony proposal

Modules

Modules

module M {
    var s = "hello";
    
    export function f() {
        return s;
    }
}

M.f();
M.s;  // Error, s is not exported


ES Harmony - Modules

module math {
    export function sum(x, y) {
        return x + y;
    }

    export var pi = 3.141593;
}    

See ES Harmony modules examples

Example -> Animal Farm!

Discussion!

Thanks to the following persons for the great pictures!

  • Picture on "Modules" slides by http://www.flickr.com/photos/sillydog/287354869/
  • Picture on "Classes and Inheritance" slides by http://www.flickr.com/photos/taylar/5145153388/
  • Picture on "Types" slides by http://www.flickr.com/photos/ccpixel/4913826800/