0% found this document useful (0 votes)
6 views23 pages

TypeScript Intro

desenvolvimento-web
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views23 pages

TypeScript Intro

desenvolvimento-web
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

TypeScript Introduction

Rainer Stropek
software architects gmbh

TypeScript

Mail
Web
Twitter

rainer@[Link]
[Link]
@rstropek

JavaScript on Steroids

Saves the day.

Why TypeScript?

JavaScript is great because of its reach


JavaScript is everywhere

JavaScript is great because of available libraries


For server and client

JavaScript (sometimes) sucks because of missing types


Limited editor support (IntelliSense)
Runtime errors instead of compile-time errors

Our wish: Productivity of robustness of C# with reach of JavaScript

What is TypeScript?

Valid JavaScript is valid TypeScript


TypeScript defines add-ons to JavaScript (primarily type information)
Existing JavaScript code works perfectly with TypeScript

TypeScript compiles into JavaScript


Compile-time error checking base on type information
Use it on servers (with [Link]), in the browser, in Windows Store apps, etc.
Generated code follows usual JavaScript patterns (e.g. pseudo-classes)

Microsoft provides great tool support


E.g. IntelliSense in VS2012

TypeScript Introduction

var n: number;
var a;
var s = "Max";
n
a
a
n

=
=
=
=

5;
5;
"Hello";
"Hello";

// no type -> Any


// Contextual typing -> string
//
//
//
//
//

valid because 5 is a number


valid because a is of type Any
valid because a is of type Any
compile time error because
"Hello" is not a number

Typing Basics
Any
Primitive Types
Number
Boolean
String

Object Types

Classes, Modules, Interfaces,

VS2012 IntelliSense based on


types

TypeScript Introduction

Typing Basics
Types are used during editing
and compiling

No type information in resulting


JavaScript code

Contextual Typing

Determine result type from


expressions automatically

What happens with types in JavaScript?


No performance impact

TypeScript Introduction

Typing Basics
TypeScript classes become
JavaScript pseudo-classes
[Link]

What happens with classes in JavaScript?


Results in the usual JavaScript pseudo-class pattern

TypeScript Introduction

Typing Basics

How do modules work?

Results in the usual JavaScript module pattern

TypeScript Introduction

module CrmModule {
// Define an interface that specifies
// what a person must consist of.
export interface IPerson {
firstName: string;
lastName: string;
}

Language Overview
Modules
Interfaces

TypeScript Introduction

export class Person implements IPerson {


private isNew: bool;
public firstName: string;
constructor(firstName: string, public lastName: string) {
[Link] = firstName;
}
public toString() { return [Link] + ", " + [Link]; }
public get isValid() {
return [Link] ||
([Link] > 0 && [Link] > 0);
}
public savePerson(repository, completedCallback: (bool) => void) {
var code = [Link](this);
completedCallback(code === 200);
}

Language Overview
Classes

Note that Person would not need to specify


implements IPerson explicitely. Even if the
implements clause would not be there,
Person would be compatible with IPerson
because of structural subtyping.

Constructor

Note the keyword public used for parameter


lastName. It makes lastName a public
property. FirstName is assigned manually.

Function Type Literal

Note the function type literal used for the


completeCallback parameter. repository has
no type. Therefore it is of type Any.

TypeScript Introduction

// Create derived classes using the "extends" keyword


export class VipPerson extends Person {
public toString() {
return [Link]() + " (VIP)";
}
}

Language Overview
Derived Classes

Note that VipPerson does not define a


constructor. It gets a constructor with
appropriate parameters from its base class
automatically.

TypeScript Introduction

module CrmModule {

// Define a nested module inside of CrmModule


export module Sales {
export class Opportunity {
public potentialRevenueEur: number;
public contacts: IPerson[];
// Array type

// Note that we use the "IPerson" interface here.


public addContact(p: IPerson) {
[Link](p);
}
// A static member...
static convertToUsd(amountInEur: number): number {
return amountInEur * 1.3;
}
}

}
}

Language Overview
Nested Modules

Note that Person would not need to specify


implements IPerson explicitly. Even if the
implements clause would not be there,
Person would be compatible with IPerson
because of structural subtyping.

TypeScript Introduction

public savePerson(repository, completedCallback: (bool) => void) {


var code = [Link](this);
completedCallback(code === 200);
}

// Call a method and pass a callback function.


var r = {
saveViaRestService: function (p: [Link]) {
alert("Saving " + [Link]());
return 200;
}
};
[Link](r, function(success: string) { alert("Saved"); });

Language Overview
Callback functions

TypeScript Introduction

export interface IPerson {


firstName: string;
lastName: string;
}

public addContact(p: IPerson) { [Link](p); }

import S = [Link];
var s: [Link];
s = new [Link]();
[Link] = 1000;
[Link](v);
[Link]({ firstName: "Rainer", lastName: "Stropek" });
[Link](<[Link]> {
firstName: "Rainer", lastName: "Stropek" });
var val = [Link]([Link]);

Language Overview
Structural Subtyping

Note structural subtyping here. You can call


addContact with any object type compatible
with IPerson.

TypeScript Introduction

Interfaces
Interfaces are only used for
editing and compiling

No type information in resulting


JavaScript code

Structural Subtyping

What happens with interfaces in JavaScript?


They are gone

TypeScript Introduction

interface JQueryEventObject extends Event {


preventDefault(): any;
}
interface JQuery {
ready(handler: any): JQuery;
click(handler: (eventObject: JQueryEventObject) => any): JQuery;
}
interface JQueryStatic {
(element: Element): JQuery;
(selector: string, context?: any): JQuery;
}

declare var $: JQueryStatic;

Interfaces
Ambient Declarations (.[Link])

External type information for


existing JavaScript libraries like
JQuery

TypeScript Type
Definition Library

See link in the resources section

TypeScript Introduction

/// <reference path="[Link]" />


$([Link]).ready(function(){
alert("Loaded");
$("a").click(function(event) {
alert("The link no longer took you to [Link]");
[Link]();
});
});

Interfaces
Ambient Declarations (.[Link])

External type information for


existing JavaScript libraries like
JQuery

TypeScript Type
Definition Library

See link in the resources section

TypeScript Introduction

export module customer {


export interface ICustomer {
firstName: string;
lastName: string;
}
export class Customer implements ICustomer {
public firstName: string;
public lastName: string;
constructor (arg: ICustomer = { firstName: "", lastName: "" }) {
[Link] = [Link];
[Link] = [Link];
}
public fullName() {
return [Link] + ", " + [Link];
}

}
}

Shared Code
Common Logic

On server ([Link])
On client (browser)

TypeScript Introduction

/// <reference path="../tsd/[Link]" />


/// <reference path="../tsd/[Link]" />
/// <reference path="./[Link]" />
import express = module("express");
import crm = module("customer");
var app = express();
[Link]("/customer/:id", function (req, resp) {
var customerId = <number>[Link];
var c = new [Link]({ firstName: "Max" +
[Link](), lastName: "Muster" });
[Link]([Link]());
[Link]([Link](c));
});

Shared Code
[Link]

Use [Link] to setup a small


web api.

TypeScript Introduction

[Link]("/customer", function (req, resp) {


var customers: [Link] [];
customers = new Array();
for (var i = 0; i<10; i++) {
[Link](new [Link](
{ firstName: "Max" + [Link](),
lastName: "Muster" }));
}
[Link]([Link](customers));
});
[Link]("/static", [Link](__dirname + "/"));
[Link](8088);

Shared Code
[Link]

Use [Link] to setup a small


web api.

TypeScript Introduction

/// <reference path="../modules/[Link]" />


import cust = module("app/classes/customer");
export class AppMain {
public run() {
$.get("[Link]
.done(function (data) {
var c = new [Link]([Link](data));
$("#fullname").text([Link]());
});
}
}

Shared Code
Browser

Uses [Link] to load modules


at runtime

So What?
TypeScript

offers you the reach of JavaScript

Stay as strongly typed as possible but as dynamic as necessary

TypeScript

makes you more productive (IntelliSense)

Ready for larger projects and larger teams

TypeScript

produces less runtime errors

Because of compile-time type checking

TypeScript

can change your view on JavaScript

Resources

Videos, Websites, Documents


[Link]
[Link]
[Link]
[Link]
[Link]
[Link]

TypeScript Type Definition Library


[Link]

Sample
[Link]

TypeScript Introduction

Rainer Stropek
software architects gmbh

Q&A

Mail
Web
Twitter

rainer@[Link]
[Link]
@rstropek

Thank You For Coming.


Saves the day.

You might also like