introduction to

Typescript

Pedro Casaubon @xperiments
BarcelonaJS



Typescript


Is a Microsoft Open Source language
that transpiles to Javascript

...describes JavaScript's dynamic types
at development time using Strong Typing

download:

typescriptlang.org



Typescript


...is "aligned" to the ES6 spec

...adds support for classes
interfaces modules enums & generics

...you can start off with JavaScript
and just add some types
here and there...

Typescript

Installation:
$ sudo npm install typescript -g 

Command line compiler:
$ tsc source.ts 

  • clean JS code
  • ES5 o ES3 ( default )
  • output to single or multiple files
  • supports AMD/CommonJS
  • definition files ( later...)

TYPESCRIPT


.ts Source files

.d.ts Definition files
( like .h in c++ )
Gives type safety, intellisense and compile errors
Can be consumed by 
third-party developers

Where ?
380 and growing....
jQuery NodeJS AngularJS Backbone Ember Vue...
https://github.com/borisyankov/DefinitelyTyped


TypeSCRIPT Annotation


basic types:
//any
var anyVar : any = /_/g;

//number
var height : number = 6;

//boolean
var isDone : boolean = false;

//string
var name : string = "bob";    

TYPE SCRIPT  ANNOTATION

Arrays

// normal declarationvar typedStringArray:string[] = [];
// Alternate declaration
var typedNumberArray:Array<number> = new Array<number>();
// Multiple dimensional Arraysvar multiDimensionalArray:CustomType[][];


Typed Arrays

var typedDict:{ [name:string]:string } = [];var typedDict:{ [name:string]:CustomClass } = [];

TYPED FUNCTIONS

// Inline declarationvar callBack:( data:string )=> void;function asyncLoad( callback:( data:any, error:string )=> void ):void { ... }
// Interface declarationinterface ICallBack{ ( data:any, error:string ):any }
function asyncLoad( callback:ICallBack ):any { ... }
// typed return typesfunction typedReturnType():SomeClass{ ... }

// Optional Paramsfunction options( optionalParam?:string ){}

// default paramsfunction method( defaultValue:number = 100 ){}

TYPE SCRIPT  ANNOTATION

REST ARGUMENTS

 // Rest argumentsfunction sum( ...nums:number[] ):number
{
	var result:number = 0;
	nums.forEach(function( num ){ result+=num });
	return result;
}var result = sum(1,2,3,4);
function sum() {
    var nums = [];
    for (var _i = 0; _i < (arguments.length - 0); _i++) {
        nums[_i] = arguments[_i + 0];
    }
    var result = 0;
    nums.forEach(function (num) {
        result += num;
    });
    return result;
}
var result = sum(1, 2, 3, 4);

TYPESCRIPT CLASSES


class Message
{
    public static COUNT: number = 0;
    public message: string;
    private senderID: number;
    constructor( message: string )
    {
        this.message = message;
        Message.incCount();
    }
    public clone(): Message
    {
        return new Message( this.message );
    }    private static incCount():void { Message.COUNT++; }}   


TYPE SCRIPT  INHEHIRANCE

class A
{
    constructor(){ console.log('SUPER CONSTRUCTOR'); }
    methodA( from:string ){ console.log('Super called from', from); }
}

class B extends A
{
    constructor()
    {
        super(); // must first call super
        console.log('DERIVED CONSTRUCTOR');

    }
    /*overload*/ methodA( from:string ){ super.methodA(from) }
    methodB(){}
}


TYPE SCRIPT  METHOD OVERLOADING



class A
{
    methodA( c:string )
    methodA( c:number )
    methodA( c:string[] )
    {
        // Must check ourselves the types        ...    }
}

TYPESCRIPT INTERFACES

interface IJSONResult {    result:string;
    code:number;}var result: IJSONResult = { result:"World", code:200 } // Pass
var result: IJSONResult = { result:"World", code:"200" } // Fail
interface B extends IJSONResult
{
   methodB();
}
class C implements A, B
{
    result:string;
    code:number;
    methodB(){}}



TYPESCRIPT INTERFACES
METHOD OVERLOADING

interface A{    method();    method(total:number);    method(total:string, sum?:number );}

TYPE SCRIPT OVERLOAD ON CONSTANTS


// included in lib.d.ts...
interface Document {
    createElement(tagName: string): HTMLElement;
    createElement(tagName: 'canvas'): HTMLCanvasElement;
    createElement(tagName: 'div'): HTMLDivElement;
    createElement(tagName: 'span'): HTMLSpanElement;
    // + 100 more
}...
// program var canv:HTMLCanvasElement = /*infered*/document.createElement('canvas'); canv.getContext('2d'); // getting intellisense here in most IDE's


TYPESCRIPT INTERFACES
INTERFACE MERGIN

interface I {
   foo(x: number): void;
   foo(x: string): void;
}interface I {
   foo(x: Date): void;
   foo(x: {abc: string}): void;
}
interface I {
   foo(x: Date): void;
   foo(x: {abc: string}): void;
   foo(x: number): void;
   foo(x: string): void;
}

TYPESCRIPT LAMBDAS

var c = ( e ) =>{ return e*e }
var c = e => e*e;

class A
{
    data:number = 10;
    c:(e)=>void = (e) =>{ e*e* this.data }
}   
var c = function (e) {
    return e * e;
};
var c = function (e) {
    return e * e;
};

var A = (function () {
    function A() {
        var _this = this;
        this.data = 10;
        this.c = function (e) {
            e * e * _this.data;
        };
    }
    return A;
})();

TYPESCRIPT ENUMS

enum Style
{
  NONE = 0,
  BOLD = 1,
  ITALIC = 2,
  UNDERLINE = 4,
  EMPHASIS = Style.BOLD | Style.ITALIC,
  HYPERLINK = Style.BOLD | Style.UNDERLINE
}    
enum Status
{
    New,
    Active,
    Disabled
}    
// get enum value
var c:number = Style.ITALIC; // 2
var d:string = Status[Status.Active]; // Active

TYPESCRIPT MODULES

scoping of variables (out of global scope)
AMD or CommonJS

module ModuleName
{
    export class SomeClass{}
}
var ModuleName;
(function (ModuleName) {
    var SomeClass = (function () {
        function SomeClass() {
        }
        return SomeClass;
    })();
    ModuleName. SomeClass = SomeClass;
})(ModuleName || (ModuleName = {}));

TYPESCRIPT GENERICS

function cast<T>( obj:any ):T
{
    return <T>obj;
}
interface A
{
    method();
}

class B implements A
{
    method(){}
}

class C{ }

function cast<T extends A>( obj:any ):T
{
    return <T>obj;
}

var a:B = cast( new B() ); // OK
var b:B = cast( new C() ); // Fail



TYPESCRIPT LIB.D.TS


interface Array<T>{
    ...
    map<U>(callbackfn: (value: T, index: number, array: T[]) => U): U[];
    ...
}

TYPESCRIPT <OBJECT POOL>

class Pool<T> {
        private pool:Array<T>;
        private counter:number;
        constructor( type:any, len:number )
        {
            this.pool = [];
            this.counter = len;
            var i:number = len;
            while (--i > -1)
                this.pool[i] = new type();
            return this;
        }
        public pop():T
        {
            if (this.counter > 0)
                return this.pool[--this.counter];
            else
                throw new Error("You exhausted the pool!");
        }
        public push( s:T ):void { this.pool[this.counter++] = s; }
        public getPool():Array { return this.pool; }
}
var carPool:Pool<Car> = new Pool<Car>( Car,1000 ); // OK
var carPool:Pool<Car> = new Pool<Bus>( Bus,1000 ); // FAIL


TYPESCRIPT IDE SUPPORT

Eclipse
IntelliJ
WebStorm
Sublime 2/3
TextMate
Atom

Static type checking.
Strong type inference.
Symbol-based navigation.
Statement completion / intellisense.
Code refactoring.

TYPESCRIPT LINKS

GRUNT-TS

A grunt task to manage your complete typescript development to production workflow

https://github.com/grunt-ts/grunt-ts  

Definitely Typed

The repository for high quality TypeScript type definitions.

https://github.com/borisyankov/DefinitelyTyped

TSD

TypeScript Definition manager for DefinitelyTyped 

http://www.tsdpm.com

JSON 2 dts

xperiments.github.io/json2dts/




THANKS

Introduction to Typescript @bcnjs

By Pedro Casaubon

Introduction to Typescript @bcnjs

  • 2,482