SlideShare a Scribd company logo
1 of 23
TypeScript Introduction



                                    Rainer Stropek
                                    software architects gmbh




TypeScript                  Mail
                            Web
                          Twitter
                                    rainer@timecockpit.com
                                    http://www.timecockpit.com
                                    @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 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
TypeScript Introduction



var n: number;                                             Typing Basics
var a;              // no type -> Any
var s = "Max";      // Contextual typing -> string
                                                           Any
n   =   5;          //    valid because 5 is a number
a   =   5;          //    valid because a is of type Any
                                                           Primitive Types
a   =   "Hello";    //    valid because a is of type Any
                                                             Number
                                                             Boolean
n   =   "Hello";    //    compile time error because
                                                             String
                    //    "Hello" is not a number

                                                           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
                                                        http://javascript.info/tutorial/pseudo-classical-pattern




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
                                          Language Overview
  // what a person must consist of.       Modules
  export interface IPerson {
    firstName: string;                    Interfaces
    lastName: string;
  }
  …
}
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.
 }
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.
TypeScript Introduction



                                                                 Language Overview
module 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;
            }
        }
    }
}
TypeScript Introduction


public 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"); });
TypeScript Introduction


export interface IPerson {
  firstName: string;                                           Language Overview
  lastName: string;
}                                                              Structural Subtyping
…                                                                Note structural subtyping here. You can call
public 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);
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;                                             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;
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
TypeScript Introduction


export 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;
        }
    }
}
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.js
import 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));
});
TypeScript Introduction


app.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);
TypeScript Introduction


/// <reference path="../modules/jquery-1.8.d.ts" />
import cust = module("app/classes/customer");
                                                                Shared Code
export 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());
      });
  }
}
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
    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
TypeScript Introduction



                                    Rainer Stropek
                                    software architects gmbh



                            Mail    rainer@timecockpit.com

Q&A                         Web
                          Twitter
                                    http://www.timecockpit.com
                                    @rstropek


Thank You For Coming.
                                    Saves the day.

More Related Content

Recently uploaded

Patch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updatePatch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updateadam112203
 
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptxGraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptxNeo4j
 
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptxEmil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptxNeo4j
 
UiPath Studio Web workshop series - Day 2
UiPath Studio Web workshop series - Day 2UiPath Studio Web workshop series - Day 2
UiPath Studio Web workshop series - Day 2DianaGray10
 
CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024Brian Pichman
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl
 
Stobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through TokenizationStobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through TokenizationStobox
 
Where developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is goingWhere developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is goingFrancesco Corti
 
AI Workshops at Computers In Libraries 2024
AI Workshops at Computers In Libraries 2024AI Workshops at Computers In Libraries 2024
AI Workshops at Computers In Libraries 2024Brian Pichman
 
Automation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projectsAutomation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projectsDianaGray10
 
UiPath Studio Web workshop series - Day 1
UiPath Studio Web workshop series  - Day 1UiPath Studio Web workshop series  - Day 1
UiPath Studio Web workshop series - Day 1DianaGray10
 
How to release an Open Source Dataweave Library
How to release an Open Source Dataweave LibraryHow to release an Open Source Dataweave Library
How to release an Open Source Dataweave Libraryshyamraj55
 
3 Pitfalls Everyone Should Avoid with Cloud Data
3 Pitfalls Everyone Should Avoid with Cloud Data3 Pitfalls Everyone Should Avoid with Cloud Data
3 Pitfalls Everyone Should Avoid with Cloud DataEric D. Schabell
 
.NET 8 ChatBot with Azure OpenAI Services.pptx
.NET 8 ChatBot with Azure OpenAI Services.pptx.NET 8 ChatBot with Azure OpenAI Services.pptx
.NET 8 ChatBot with Azure OpenAI Services.pptxHansamali Gamage
 
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechWebinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechProduct School
 
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInOutage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInThousandEyes
 
LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0DanBrown980551
 
Flow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First FrameFlow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First FrameKapil Thakar
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
 

Recently uploaded (20)

Patch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updatePatch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 update
 
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptxGraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
 
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptxEmil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
 
UiPath Studio Web workshop series - Day 2
UiPath Studio Web workshop series - Day 2UiPath Studio Web workshop series - Day 2
UiPath Studio Web workshop series - Day 2
 
CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile Brochure
 
Stobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through TokenizationStobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
 
Where developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is goingWhere developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is going
 
AI Workshops at Computers In Libraries 2024
AI Workshops at Computers In Libraries 2024AI Workshops at Computers In Libraries 2024
AI Workshops at Computers In Libraries 2024
 
Automation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projectsAutomation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projects
 
UiPath Studio Web workshop series - Day 1
UiPath Studio Web workshop series  - Day 1UiPath Studio Web workshop series  - Day 1
UiPath Studio Web workshop series - Day 1
 
How to release an Open Source Dataweave Library
How to release an Open Source Dataweave LibraryHow to release an Open Source Dataweave Library
How to release an Open Source Dataweave Library
 
3 Pitfalls Everyone Should Avoid with Cloud Data
3 Pitfalls Everyone Should Avoid with Cloud Data3 Pitfalls Everyone Should Avoid with Cloud Data
3 Pitfalls Everyone Should Avoid with Cloud Data
 
.NET 8 ChatBot with Azure OpenAI Services.pptx
.NET 8 ChatBot with Azure OpenAI Services.pptx.NET 8 ChatBot with Azure OpenAI Services.pptx
.NET 8 ChatBot with Azure OpenAI Services.pptx
 
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechWebinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
 
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInOutage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
 
SheDev 2024
SheDev 2024SheDev 2024
SheDev 2024
 
LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0
 
Flow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First FrameFlow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First Frame
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 

Featured

How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...DevGAMM Conference
 
Barbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationBarbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationErica Santiago
 
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them wellGood Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them wellSaba Software
 
Introduction to C Programming Language
Introduction to C Programming LanguageIntroduction to C Programming Language
Introduction to C Programming LanguageSimplilearn
 

Featured (20)

How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
 
Barbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationBarbie - Brand Strategy Presentation
Barbie - Brand Strategy Presentation
 
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them wellGood Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
 
Introduction to C Programming Language
Introduction to C Programming LanguageIntroduction to C Programming Language
Introduction to C Programming Language
 

TypeScript - JavaScript on Steroids

  • 1. TypeScript Introduction Rainer Stropek software architects gmbh TypeScript Mail Web Twitter rainer@timecockpit.com http://www.timecockpit.com @rstropek JavaScript on Steroids Saves the day.
  • 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. 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. TypeScript Introduction var n: number; Typing Basics var a; // no type -> Any var s = "Max"; // Contextual typing -> string Any n = 5; // valid because 5 is a number a = 5; // valid because a is of type Any Primitive Types a = "Hello"; // valid because a is of type Any Number Boolean n = "Hello"; // compile time error because String // "Hello" is not a number Object Types Classes, Modules, Interfaces, … VS2012 IntelliSense based on types
  • 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 automatically What happens with types in JavaScript? No performance impact 
  • 6. TypeScript Introduction Typing Basics TypeScript classes become JavaScript pseudo-classes http://javascript.info/tutorial/pseudo-classical-pattern What happens with classes in JavaScript? Results in the usual JavaScript pseudo-class pattern
  • 7. TypeScript Introduction Typing Basics How do modules work? Results in the usual JavaScript module pattern
  • 8. TypeScript Introduction module CrmModule { // Define an interface that specifies Language Overview // what a person must consist of. Modules export interface IPerson { firstName: string; Interfaces lastName: string; } … }
  • 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. 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. TypeScript Introduction Language Overview module 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. TypeScript Introduction public 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. TypeScript Introduction export interface IPerson { firstName: string; Language Overview lastName: string; } Structural Subtyping … Note structural subtyping here. You can call public 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. 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…
  • 15. TypeScript Introduction interface 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. 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. TypeScript Introduction export 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. 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.js import 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. TypeScript Introduction app.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. TypeScript Introduction /// <reference path="../modules/jquery-1.8.d.ts" /> import cust = module("app/classes/customer"); Shared Code export 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. 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. 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. TypeScript Introduction Rainer Stropek software architects gmbh Mail rainer@timecockpit.com Q&A Web Twitter http://www.timecockpit.com @rstropek Thank You For Coming. Saves the day.