1 of 36

TypeScript

Typed Javascript (ES6)

2 of 36

Plan

  1. Introduction
  2. Type annotations
  3. ES6 features
  4. AMD with Require.js

3 of 36

A little bit of history

C#

1.0

delegates properties

2.0

generics�

3.0

LINQ

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

4.0

dynamic

5.0

async/await

ASP.Net

1.0

WebForms

2.0

MasterPages

3.5

AJAX

1.0

MVC

2.0

3.0

4.0

2014

5.0

ASP.Net MVC�Javascript

Silverlight

1.0

2.0

3.0

4.0

5.0

4 of 36

Introduction

  • Typescript
  • Cost:
    • Optional typing
  • Value:
    • Compile-time checking
    • Autocompletion
    • Refactoring
    • Goto Definition
    • Find all references

5 of 36

Introduction

  • Open Source
    • http://typescript.codeplex.com/
    • Node.js
  • Programing
    • Visual Studio / Monaco
    • Webstorm
    • Cloud9 IDE / Eclipse
    • Sublime Text / Emacs / Vim

  • Debugging (Source maps)
    • Chrome
    • Firefox
    • Internet Explorer (VS only)

6 of 36

Introduction

  • Javascript → Typescript
    • Strict superset
    • Aligned with upcoming ECMAscript 6 features
      • Classes
      • Modules
      • Lambdas
      • Iterators?
    • Works with the current libraries*

easy way in

7 of 36

Introduction

* Typescript definition files (.d.ts) required to have strongly typed benefits, � available on https://github.com/borisyankov/DefinitelyTyped

300+ libs

300+ libs

8 of 36

Introduction

  • Typescript → Javascript
    • Compiled to idiomatic Javascript
    • No framework
    • Standard modularity
      • <script src=”...”/>
      • CommonJS (node.js)
      • AMD (require.js)

easy way out

9 of 36

Javascript alternatives

Language

Ruby syntax

No types

Language

Javascript syntax

Optional Static

Platform

Java syntax

Optional Static

10 of 36

Introduction

ren *.js *.ts

My advice:

11 of 36

Type inference

var a = “Hi”;

var a: string = “Hi”;

function Greet(name){

return “Hi ” + name;

}

function Greet(name) : string {

return “Hi ” + name;

}

function Greet(name: string) : string{

return “Hi ” + name;

}

12 of 36

Basic types

string

number int float

boolean

any

13 of 36

Structural typing

var person = {

id : 2,

name : “Bob”

};

var person : { id: number; name: string} = {

id : 2,

name : “Bob”

};

14 of 36

Any vs {}: Popularity contest

object

dynamic

any

{ }

Typescript

C#

15 of 36

Function Types

//function declaration

function add (a : number, b: number) : number { return a + b; }�

//function declaration as value

var add = function(a : number, b: number) { return a - b; }�

//function type as callable object

var add : {(a : number, b: number) => number};�

//function type as callable object allows array

var adds : {(a : number, b: number) => number}[];

//function type (in C# is Func<int,int,int>)

var add : (a : number, b: number) => number;

16 of 36

Arrays and Generics

var myArray = [1,2,3];

var myArray : number[] = [1,2,3];

var myArray : Array<number> = [1,2,3];

var myPromise : Promise<T>;

var mySelector : D3.Selector<T>;

var observable: KnockoutObservable<T>;

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

}

Generic information is removed once compiled to javascript

public static IEnumerable<R> Select<T, R>(� this IEnumerable<T> source, � Func<T, int, T> selector)

//C# equivalent

17 of 36

Casting

var element = $(“form”)[0]; //Element

formElement.submit();

var formElement = <HTMLFormElement> $(“form”)[0]

formElement.submit();

Castings are removed once compiled to javascript

Any doesn't need cast → Cast are not that common

18 of 36

Quiz

(<{}[]>a)

What does it mean?

Cast ‘a’ to array of object

19 of 36

Interfaces

    • A name for a type declaration
    • Disappear on compilation

//File.d.ts�interface PersonData {

id: number;

name: string;

}

//OtherFile.ts

interface PersonData {

dateOfBirth: Date;

}

    • Open ended

20 of 36

Indexers and Callable objects

Indexers

interface Dictionary {

[value: string]: string;

}

Callable objects

interface JQueryStatic {

(selector: string) : JQuery;

}

interface JQueryStatic {

(domReady: () => void): void;

}

obj.Name

obj[“Name”]

21 of 36

Optional members / arguments

interface PersonData {

id: number;

name: string;

dateOfBirth? : Date�

}

var person1 : PersonData = { id: 3, name: “Bob”, dateOfBirth: new Date() };var person2 : PersonData = { id: 3, name: null};�var person3 : PersonData = { id: 3 };�

�����

new(id: number, name: string, dateOfBirth?: Date) : PersonData;

���var person1c = new PersonData(2, “Bob”, new Date()); �var person2c = new PersonData(2, null); �var person3c = new PersonData(2);

22 of 36

Declaration files (.d.ts)

Subset of Typescript with declarative-only instructions

  • Interfaces
  • Variable declarations
  • Module declarations

Like *.h files for existing *.js libraries

/// <reference path="../Headers/jquery/jquery.d.ts"/>

/// <reference path="../MyTSLibrary.ts"/>

23 of 36

ECMAscript 6 features

  1. Classes
  2. Lambdas
  3. Iterators?
  4. Modules

24 of 36

Classes

  • prototypal method implementation
  • public by default
  • private is a fake
  • this is mandatory
  • less expressive than interfaces!

class Person

{

id: number; �name: string;�constructor(id: number){

this.id = id;

}

toString(){ return this.name;}

}

Person

toString: function...

id: 10

name: “Bob”

25 of 36

Classes (inheritance)

  • prototypal inheritance made easy
  • no protected
  • no override/virtual
  • constructor inheritance

class Person

{

id: number; �name: string;�constructor(id: number){

this.id = id;

}

toString(){ return this.name;}

}

class Worker extends Person

{

position: string;

toString(){

return this.name + this.position;

}

}

Person

toString: function...

id: 10

name: “Bob”

Worker

toString: function...

id: 12

name: “Satya”

positon: “CEO”

26 of 36

Lambdas

var add : (a : number, b: number) => number;

add = (a : number, b: number) => a + b;

add = (a, b) => a + b;

add = (a, b) => { return a + b};

createPerson = (id, name) => {id: id; name: name}; //ERROR!

createPerson = (id, name) => ({id: id; name: name});

27 of 36

Lambdas + this

function

lambda

class Person

{

id: number;

name: string;

findName(){

var me = this;

$.get(“/GetName”, {id : id},

function(data) { me.name = data; });

}

}

class Person

{

id: number;

name: string;

findName(){

$.get(“/GetName”, {id : id},

(data) => this.name = data);

}

}

class Person

{

id: number;

name: string;

findName(){

$.get(“/GetName”, {id : id},

function(data) { this.name = data; });

}

}

28 of 36

Promise<T>, Async and Iterators

//Traditional

var me = this;

$.get(“/GetName”, {id : id}, function(data) { me.name = data; });

//Lambda

$.get(“/GetName”, {id : id}, data => this.name = data);

Future

//Promise

$.get(“/GetName”, {id : id}).then(data => this.name = data);

//C#-ish using Promise

this.name = await $.get(“/GetName”, {id : id});

//ES6-ish using Promise

this.name = yield $.get(“/GetName”, {id : id});

Future

http://www.html5rocks.com/en/tutorials/es6/promises/?redirect_from_locale=hr

29 of 36

Modules

  • Static objects that contain other objects (~namespaces)
  • Avoid polluting the global scope
  • Keep things private using javascript IIFE

//MathBasic.js

module MathUtils {

export function mult(a: number, b: number){� return a * b;� }

}

MathUtils.add(1, MathUtils.mult(3, 2))

//MathBasic.js

module MathUtils {

export function add(a: number, b: number){� return a + b;� }�}

  • Open ended!

30 of 36

Class public vs Module export

classes

modules

public / private

export / -

not translated to javascript, only for autocompletion/compilation checking

translated to an assignment* to the module object, getting outside of the IIFE

fields, methods...

interfaces, variables, functions, sub modules...

be aware of �top level exports!!..

31 of 36

AMD with Require.js

  • Asynchronous Module Definition
  • Each file is a module (~assembly)
  • Dependencies between files are explicit
  • Files are loaded asynchronously

<script src=”myLibrary.js”/>�<script>� MyNamespace.myFunc();�</script>

<script>�require(["myLibrary"], function(myLibrary) {� myLibrary.myFunc();�});�</script>

32 of 36

Require.js: define vs require

//myLibrary.js�define(["jQuery", “exports”], function($, export) {� exports.myFunc = function() { $(“...”) };�});�

//index.htmlrequire(["myLibrary"], function(myLibrary) {� myLibrary.myFunc();�});�

33 of 36

AMD with Require.js

<script src=”...”>

Require.js / CommonJS

.js file

internal module

.js file = external module

jQuery

shim

34 of 36

AMD with Require.js + Typescript

//myLibrary.ts�import $ = require("jQuery")export myFunc = function() { $(“...”) };

//myLibrary.js�define(["jQuery", “exports”], function($, export) {� exports.myFunc = function() { $(“...”) };�});��//index.htmlrequire(["myLibrary"], function(myLibrary) {� myLibrary.myFunc();�});

35 of 36

AMD with Require.js + Typescript

  • External modules are .ts files with imports or top-level export

  • External modules:
    • Can not be referenced using /// <reference path="MyLib.ts"/>
    • Can not be referenced using <script src=”MyLib.js”/>
    • Only with import Entities = require("MyLib")

  • Why something so important is so implicit?
    • Typescript shines more on large apps
    • There, external modules (AMD / Require.js) are a must

http://blorkfish.wordpress.com/2012/10/23/typescript-organizing-your-code-with-amd-modules-and-require-js/

36 of 36

THE END

Questions?