TypeScript - JavaScript on Steroids


Published on

If JavaScript matters to you, you should definitively check out TypeScript. In this talk I introduce the new language and show practical demos for browser and node.js. You can download the samples from my blog at http://www.software-architects.com

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

TypeScript - JavaScript on Steroids

  1. 1. TypeScript Introduction Rainer Stropek software architects gmbhTypeScript Mail Web Twitter rainer@timecockpit.com http://www.timecockpit.com @rstropekJavaScript on Steroids Saves the day.
  2. 2. 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
  3. 3. 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 node.js), 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
  4. 4. TypeScript Introductionvar n: number; Typing Basicsvar a; // no type -> Anyvar s = "Max"; // Contextual typing -> string Anyn = 5; // valid because 5 is a numbera = 5; // valid because a is of type Any Primitive Typesa = "Hello"; // valid because a is of type Any Number Booleann = "Hello"; // compile time error because String // "Hello" is not a number Object Types Classes, Modules, Interfaces, … VS2012 IntelliSense based on types
  5. 5. 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 automaticallyWhat happens with types inJavaScript?No performance impact 
  6. 6. TypeScript Introduction Typing Basics TypeScript classes become JavaScript pseudo-classes http://javascript.info/tutorial/pseudo-classical-patternWhat happens with classes inJavaScript?Results in the usual JavaScript pseudo-class pattern
  7. 7. TypeScript Introduction Typing BasicsHow do modules work?Results in the usual JavaScript module pattern
  8. 8. TypeScript Introductionmodule CrmModule { // Define an interface that specifies Language Overview // what a person must consist of. Modules export interface IPerson { firstName: string; Interfaces lastName: string; } …}
  9. 9. TypeScript Introduction Language Overview export class Person implements IPerson { private isNew: bool; public firstName: string; constructor(firstName: string, public lastName: string) { Classes Note that Person would not need to specify this.firstName = firstName; implements IPerson explicitely. Even if the } implements clause would not be there, Person would be compatible with IPerson public toString() { return this.lastName + ", " + this.firstName; } because of structural subtyping. public get isValid() { Constructor return this.isNew || Note the keyword public used for parameter (this.firstName.length > 0 && this.lastName.length > 0); lastName. It makes lastName a public } property. FirstName is assigned manually. public savePerson(repository, completedCallback: (bool) => void) { Function Type Literal var code = repository.saveViaRestService(this); Note the function type literal used for the completedCallback(code === 200); completeCallback parameter. repository has } no type. Therefore it is of type Any. }
  10. 10. TypeScript Introduction // Create derived classes using the "extends" keyword export class VipPerson extends Person { Language Overview public toString() { return super.toString() + " (VIP)"; Derived Classes Note that VipPerson does not define a } constructor. It gets a constructor with } appropriate parameters from its base class automatically.
  11. 11. TypeScript Introduction Language Overviewmodule CrmModule { … // Define a nested module inside of CrmModule export module Sales { Nested Modules Note that Person would not need to specify export class Opportunity { implements IPerson explicitly. Even if the public potentialRevenueEur: number; implements clause would not be there, public contacts: IPerson[]; // Array type Person would be compatible with IPerson because of structural subtyping. // Note that we use the "IPerson" interface here. public addContact(p: IPerson) { this.contacts.push(p); } // A static member... static convertToUsd(amountInEur: number): number { return amountInEur * 1.3; } } }}
  12. 12. TypeScript Introductionpublic savePerson(repository, completedCallback: (bool) => void) { var code = repository.saveViaRestService(this); Language Overview completedCallback(code === 200); } Callback functions…// Call a method and pass a callback function.var r = { saveViaRestService: function (p: CrmModule.Person) { alert("Saving " + p.toString()); return 200; }};p.savePerson(r, function(success: string) { alert("Saved"); });
  13. 13. TypeScript Introductionexport interface IPerson { firstName: string; Language Overview lastName: string;} Structural Subtyping… Note structural subtyping here. You can callpublic addContact(p: IPerson) { this.contacts.push(p); } addContact with any object type compatible with IPerson.…import S = CrmModule.Sales;var s: S.Opportunity;s = new S.Opportunity();s.potentialRevenueEur = 1000;s.addContact(v);s.addContact({ firstName: "Rainer", lastName: "Stropek" });s.addContact(<CrmModule.IPerson> { firstName: "Rainer", lastName: "Stropek" });var val = S.Opportunity.convertToUsd(s.potentialRevenueEur);
  14. 14. TypeScript Introduction Interfaces Interfaces are only used for editing and compiling No type information in resulting JavaScript code Structural SubtypingWhat happens with interfaces in JavaScript?They are gone…
  15. 15. TypeScript Introductioninterface JQueryEventObject extends Event { preventDefault(): any; Interfaces} Ambient Declarations (.d.ts)interface JQuery { External type information for ready(handler: any): JQuery; existing JavaScript libraries like click(handler: (eventObject: JQueryEventObject) => any): JQuery; JQuery}interface JQueryStatic { TypeScript Type (element: Element): JQuery; Definition Library (selector: string, context?: any): JQuery; See link in the resources section}declare var $: JQueryStatic;
  16. 16. TypeScript Introduction/// <reference path="jQuery.d.ts" /> Interfaces$(document.body).ready(function(){ alert("Loaded"); Ambient Declarations (.d.ts) $("a").click(function(event) { External type information for alert("The link no longer took you to timecockpit.com"); existing JavaScript libraries like event.preventDefault(); JQuery });}); TypeScript Type Definition Library See link in the resources section
  17. 17. TypeScript Introductionexport module customer { export interface ICustomer { Shared Code firstName: string; lastName: string; Common Logic… } On server (node.js) On client (browser) export class Customer implements ICustomer { public firstName: string; public lastName: string; constructor (arg: ICustomer = { firstName: "", lastName: "" }) { this.firstName = arg.firstName; this.lastName = arg.lastName; } public fullName() { return this.lastName + ", " + this.firstName; } }}
  18. 18. TypeScript Introduction/// <reference path="../tsd/node-0.8.d.ts" />/// <reference path="../tsd/express-3.0.d.ts" /> Shared Code/// <reference path="./customer.ts" />import express = module("express"); Node.jsimport crm = module("customer"); Use express.js to setup a small web api.var app = express();app.get("/customer/:id", function (req, resp) { var customerId = <number>req.params.id; var c = new crm.customer.Customer({ firstName: "Max" +customerId.toString(), lastName: "Muster" }); console.log(c.fullName()); resp.send(JSON.stringify(c));});
  19. 19. TypeScript Introductionapp.get("/customer", function (req, resp) { var customers: crm.customer.Customer []; Shared Code customers = new Array(); for (var i = 0; i<10; i++) { Node.js customers.push(new crm.customer.Customer( Use express.js to setup a small { firstName: "Max" + i.toString(), web api. lastName: "Muster" })); } resp.send(JSON.stringify(customers));});app.use("/static", express.static(__dirname + "/"));app.listen(8088);
  20. 20. TypeScript Introduction/// <reference path="../modules/jquery-1.8.d.ts" />import cust = module("app/classes/customer"); Shared Codeexport class AppMain { Browser public run() { Uses require.js to load modules $.get("http://localhost:8088/Customer/99") at runtime .done(function (data) { var c = new cust.customer.Customer(JSON.parse(data)); $("#fullname").text(c.fullName()); }); }}
  21. 21. 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
  22. 22. Resources Videos, Websites, Documents http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript http://channel9.msdn.com/posts/Anders-Hejlsberg-Steve-Lucco-and-Luke-Hoban-Inside-TypeScript http://www.typescriptlang.org/ http://www.typescriptlang.org/Playground/ http://www.typescriptlang.org/Samples/ http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf TypeScript Type Definition Library https://github.com/borisyankov/DefinitelyTyped Sample http://bit.ly/TypeScriptSample
  23. 23. TypeScript Introduction Rainer Stropek software architects gmbh Mail rainer@timecockpit.comQ&A Web Twitter http://www.timecockpit.com @rstropekThank You For Coming. Saves the day.