SlideShare una empresa de Scribd logo
1 de 17
TypeScript
 for dummies?



                Ing. Santiago Aguiar
                saguiar@infragistics.com
¿Qué es TypeScript?
• Un lenguaje + compilador que genera Javascript
• Desarrollado por Microsoft y diseñado por Anders
  Hejlsberg (Pascal, Delphi, C#)
    Microsoft?!
       “I fully expect to find their grandmother under the bus along
       with Silverlight! ”, someone@google+
    Open Source
      Compiler + Tooling: Apache 2.0 License
      Especificación: OWF
       http://typescript.codeplex.com/
Qué aporta….?
• Superset de JavaScript
   o Todo código JS es código TS válido ...casi
• Compile-time type checking, opcional ...casi
• Construcciones de ECMAScript 6:
   o   Módulos
   o   Clases y OOP
   o   Lambdas
   o   No mucho más…
• Tooling: completion, refactoring, navigation.
Cross-platform?
• Compilador y language services escritos en
  TypeScript

• Plugin de node.js ejecutable desde shell:
  > tsc file.ts

• Reusable desde cualquier entorno donde pueda
  ejecutar Javascript
Tooling fuera de VS
ACE Editor




TypeScript Playground

...
Vim / Emacs / Sublime 2?
El lenguaje
• Declaración de Tipos
• Clases y herencia
• Interfaces & Structural Typing
• Módulos
• Lambdas (arrow expressions)
• Integración con librerías de JS
• Futuro: generics & constant overloads
var name: string;
name = 0;
name = "foo";
var point: { x: number; y: number; z?: number; };
                                                        Tipos
point = { x: "0", z: 1};
point = { x: 1, y: 2};

function move(point: { x: number; y: number; }, delta: number) {
       return { x: point.x + delta, y: point.y + delta };
}

point = move(point, 5);

var names: string[] = [];
names.push(1);
names.push("foo");

// contextual typing
var alias: (point: { x: number; y: number; }, delta: number) => any;
alias = moveIt;
alias = (point, delta) => point.x;
Clases
class User {                                                    var User = (function () {
 constructor(public name: string) {                                 function User(name) {
 }                                                                      this.name = name;
}                                                                   }




                                                   Javascript
                                                                    return User;



                                      TypeScript
                                                                })();


class Participant extends User {                                var Participant = (function (_super){
  invited: bool;                                                    __extends(Participant, _super);
  constructor(name: string) {                                       function Participant(name) {
      super(name);                                                      _super.call(this, name);
  }                                                                 }
}                                                                   return Participant;
                                                                })(User);
class Meetup {
    static Version = "1.0";
    private _date: Date;

    constructor(date?: Date) {
        this._date = date || new Date();
                                                         Miembros
    }

    get date() { return this._date; }
    set date(newDate: Date) { return this._date = newDate; }

    postpone(date: Date);
    postpone(day: number, month: number);
    postpone() {
        if (arguments.length === 1) {
            this.date = arguments[0];
        }
        else {
            this.date.setDate(arguments[0]);
            this.date.setMonth(arguments[1] - 1);
        }
        this.notifyPostponed();
    }

    private notifyPostponed() { alert('Postponed!'); }
}
Interfaces &
                          Structural Typing
interface Point {
    x: number;
    y: number;
}

function move(point: Point, delta: number) {
    return new MyPoint(point.x + delta, point.y + delta);
}

class MyPoint implements Point {
    constructor(x: number, y: number);
}

var implicitPoint = move({ x: 1, y: 1 }, 5); // structural typing

var point = move(new MyPoint(1, 1), 5);
Módulos
ModuleA.ts
                                                            define(["require", "exports"],
export function DoTheA() {                                  function(require, exports) {
    return 'AAAA!';                                             function DoTheA() {
}                                                                   return 'AAAA!';
                                                                } Implementado por
                                                                exports.DoTheA = DoTheA;
function DoThePrivateA() {                                            RequireJS /



                                               Javascript
                                  TypeScript
                                                                function DoThePrivateA() {
    return '(aaaa)';                                                  CommonJS
                                                                    return '(aaaa)';
                                                                }
}
                                                            })

ModuleB.ts                                                  define(["require", "exports", 'ModuleA'],
                                                            function(require, exports, __a__) {
import a = module('ModuleA');                                   var a = __a__;

export function DoTheBA() {                                      function DoTheBA() {
    return 'BBBB' + a.DoTheA();                                      return 'BBBB' + a.DoTheA();
                                                                 }
}                                                                exports.DoTheBA = DoTheBA;
                                                            })
Lambdas
TypeScript
this._participants.forEach(p => this.invite(p));
this._participants.forEach(p => this.invite(p));

Javascript
var _this = this;
this._participants.forEach(function (p) {
    return _this.invite(p);
})
Una library en JS: external.js
AnUglyGlobal = function (value) {          JS Libraries
    this.field = value;
} // a constructor
AnUglyGlobal.prototype.doIt = function(x) {
    return this.field + x;                            DefinitelyTyped
} // a method                                         define los tipos de
                                                      más de 130 libraries
La declaración de la library para TS: external.d.ts
interface UglyGlobal {                                Angular, underscore,
    field: string;                                    Jquery, ember,
    doIt(value: string);                              Knockout, etc..
}
                                                      https://github.com/borisyank
declare var AnUglyGlobal : UglyGlobal;
                                                      ov/DefinitelyTyped

El código TS que usa la library: uses_external.ts
 /// <reference path="external.d.ts"/>
 AnUglyGlobal.doIt("foo");
Muy lindo, pero ya existe…
• CoffeeScript
  o No es JS. No hay type checking.

• Closure
  o Anotaciones en la documentación. Algo más ‘verboso’. Optimizador.

• Traceur
  o Diseñado para experimentar con
    construcciones futuras de ES.
  o No hay type checking.
  o Pocas consideraciones sobre el
    código generado

• Dart
  o Require un runtime, más ambicioso y menos JS.
Type Checking?
Douglas Crockford:
 Microsoft's TypeScript may be the best of the many
 JavaScript front ends. (…) it seems to generate the most
 attractive code. (…) it should take pressure off of the
 ECMAScript Standard for new features like type declarations and
 classes. (…) these can be provided nicely by a preprocessor, so
 there is no need to change the underlying language.


 I think that JavaScript's loose typing is one of its best
 features and that type checking is way overrated.
 TypeScript adds sweetness, but at a price. It is not a price I am
 willing to pay.
Por qué lo elegimos?
• Implementado un diseño OO existente.
• No queríamos tener que inventar nuestra propia
  forma de definir clases, herencia, o de definición de
  módulos.
• Dispuestos a aceptar mejoras sobre JS poco intrusivas
  (opt-out), que se integren bien con nuestro entorno
  actual.
• No queríamos que todo el equipo aprendiera un nuevo
  lenguaje, preferíamos algo familiar.
• Type Checking :)
Links
•   TypeScript source code (http://typescript.codeplex.com/)
•   TypeScript Playground (http://www.typescriptlang.org/Playground/)
•   Ace editor (http://ace.ajax.org/, https://github.com/hi104/typescript-
    playground-on-ace)
•   CofeeScript: http://coffeescript.org/
•   Closure: https://developers.google.com/closure/compiler/

•   Traceur: https://code.google.com/p/traceur-compiler/, http://traceur-
    compiler.googlecode.com/git/demo/repl.html
•   Me: saguiar@infragistics.com

Más contenido relacionado

La actualidad más candente

Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Sylvain Wallez
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to DartRamesh Nair
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityGeorgePeterBanyard
 
Introduction to JRuby
Introduction to JRubyIntroduction to JRuby
Introduction to JRubyelliando dias
 
.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#Bertrand Le Roy
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17LogeekNightUkraine
 
Better DSL Support for Groovy-Eclipse
Better DSL Support for Groovy-EclipseBetter DSL Support for Groovy-Eclipse
Better DSL Support for Groovy-EclipseAndrew Eisenberg
 
Shiksharth com java_topics
Shiksharth com java_topicsShiksharth com java_topics
Shiksharth com java_topicsRajesh Verma
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Guillaume Laforge
 
Introducing type script
Introducing type scriptIntroducing type script
Introducing type scriptRemo Jansen
 
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI векеДмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI векеSergey Platonov
 
GOCON Autumn (Story of our own Monitoring Agent in golang)
GOCON Autumn (Story of our own Monitoring Agent in golang)GOCON Autumn (Story of our own Monitoring Agent in golang)
GOCON Autumn (Story of our own Monitoring Agent in golang)Huy Do
 
Typescript Fundamentals
Typescript FundamentalsTypescript Fundamentals
Typescript FundamentalsSunny Sharma
 
TypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponLaurent Duveau
 
Hourglass Interfaces for C++ APIs - CppCon 2014
Hourglass Interfaces for C++ APIs - CppCon 2014Hourglass Interfaces for C++ APIs - CppCon 2014
Hourglass Interfaces for C++ APIs - CppCon 2014Stefanus Du Toit
 
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume LaforgeGR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume LaforgeGR8Conf
 

La actualidad más candente (20)

Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to Dart
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing Insanity
 
Introduction to JRuby
Introduction to JRubyIntroduction to JRuby
Introduction to JRuby
 
XAML/C# to HTML/JS
XAML/C# to HTML/JSXAML/C# to HTML/JS
XAML/C# to HTML/JS
 
.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
 
Better DSL Support for Groovy-Eclipse
Better DSL Support for Groovy-EclipseBetter DSL Support for Groovy-Eclipse
Better DSL Support for Groovy-Eclipse
 
Shiksharth com java_topics
Shiksharth com java_topicsShiksharth com java_topics
Shiksharth com java_topics
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007
 
Introducing type script
Introducing type scriptIntroducing type script
Introducing type script
 
TypeScript intro
TypeScript introTypeScript intro
TypeScript intro
 
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI векеДмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI веке
 
GOCON Autumn (Story of our own Monitoring Agent in golang)
GOCON Autumn (Story of our own Monitoring Agent in golang)GOCON Autumn (Story of our own Monitoring Agent in golang)
GOCON Autumn (Story of our own Monitoring Agent in golang)
 
Typescript Fundamentals
Typescript FundamentalsTypescript Fundamentals
Typescript Fundamentals
 
El viaje de Angular1 a Angular2
El viaje de Angular1 a Angular2El viaje de Angular1 a Angular2
El viaje de Angular1 a Angular2
 
TypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret Weapon
 
Hourglass Interfaces for C++ APIs - CppCon 2014
Hourglass Interfaces for C++ APIs - CppCon 2014Hourglass Interfaces for C++ APIs - CppCon 2014
Hourglass Interfaces for C++ APIs - CppCon 2014
 
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume LaforgeGR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
 
TypeScript
TypeScriptTypeScript
TypeScript
 

Similar a Type script, for dummies

TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
No JS and DartCon
No JS and DartConNo JS and DartCon
No JS and DartConanandvns
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs偉格 高
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
JSLounge - TypeScript 소개
JSLounge - TypeScript 소개JSLounge - TypeScript 소개
JSLounge - TypeScript 소개Reagan Hwang
 
TypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyTypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyRalph Johnson
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptMiao Siyu
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
05 pig user defined functions (udfs)
05 pig user defined functions (udfs)05 pig user defined functions (udfs)
05 pig user defined functions (udfs)Subhas Kumar Ghosh
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java DevelopersYakov Fain
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()daewon jeong
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)Eduard Tomàs
 

Similar a Type script, for dummies (20)

TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Dart
DartDart
Dart
 
No JS and DartCon
No JS and DartConNo JS and DartCon
No JS and DartCon
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
JSLounge - TypeScript 소개
JSLounge - TypeScript 소개JSLounge - TypeScript 소개
JSLounge - TypeScript 소개
 
TypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyTypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason Haffey
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
05 pig user defined functions (udfs)
05 pig user defined functions (udfs)05 pig user defined functions (udfs)
05 pig user defined functions (udfs)
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 

Último (20)

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

Type script, for dummies

  • 1. TypeScript for dummies? Ing. Santiago Aguiar saguiar@infragistics.com
  • 2. ¿Qué es TypeScript? • Un lenguaje + compilador que genera Javascript • Desarrollado por Microsoft y diseñado por Anders Hejlsberg (Pascal, Delphi, C#) Microsoft?! “I fully expect to find their grandmother under the bus along with Silverlight! ”, someone@google+ Open Source Compiler + Tooling: Apache 2.0 License Especificación: OWF http://typescript.codeplex.com/
  • 3. Qué aporta….? • Superset de JavaScript o Todo código JS es código TS válido ...casi • Compile-time type checking, opcional ...casi • Construcciones de ECMAScript 6: o Módulos o Clases y OOP o Lambdas o No mucho más… • Tooling: completion, refactoring, navigation.
  • 4. Cross-platform? • Compilador y language services escritos en TypeScript • Plugin de node.js ejecutable desde shell: > tsc file.ts • Reusable desde cualquier entorno donde pueda ejecutar Javascript
  • 5. Tooling fuera de VS ACE Editor TypeScript Playground ... Vim / Emacs / Sublime 2?
  • 6. El lenguaje • Declaración de Tipos • Clases y herencia • Interfaces & Structural Typing • Módulos • Lambdas (arrow expressions) • Integración con librerías de JS • Futuro: generics & constant overloads
  • 7. var name: string; name = 0; name = "foo"; var point: { x: number; y: number; z?: number; }; Tipos point = { x: "0", z: 1}; point = { x: 1, y: 2}; function move(point: { x: number; y: number; }, delta: number) { return { x: point.x + delta, y: point.y + delta }; } point = move(point, 5); var names: string[] = []; names.push(1); names.push("foo"); // contextual typing var alias: (point: { x: number; y: number; }, delta: number) => any; alias = moveIt; alias = (point, delta) => point.x;
  • 8. Clases class User { var User = (function () { constructor(public name: string) { function User(name) { } this.name = name; } } Javascript return User; TypeScript })(); class Participant extends User { var Participant = (function (_super){ invited: bool; __extends(Participant, _super); constructor(name: string) { function Participant(name) { super(name); _super.call(this, name); } } } return Participant; })(User);
  • 9. class Meetup { static Version = "1.0"; private _date: Date; constructor(date?: Date) { this._date = date || new Date(); Miembros } get date() { return this._date; } set date(newDate: Date) { return this._date = newDate; } postpone(date: Date); postpone(day: number, month: number); postpone() { if (arguments.length === 1) { this.date = arguments[0]; } else { this.date.setDate(arguments[0]); this.date.setMonth(arguments[1] - 1); } this.notifyPostponed(); } private notifyPostponed() { alert('Postponed!'); } }
  • 10. Interfaces & Structural Typing interface Point { x: number; y: number; } function move(point: Point, delta: number) { return new MyPoint(point.x + delta, point.y + delta); } class MyPoint implements Point { constructor(x: number, y: number); } var implicitPoint = move({ x: 1, y: 1 }, 5); // structural typing var point = move(new MyPoint(1, 1), 5);
  • 11. Módulos ModuleA.ts define(["require", "exports"], export function DoTheA() { function(require, exports) { return 'AAAA!'; function DoTheA() { } return 'AAAA!'; } Implementado por exports.DoTheA = DoTheA; function DoThePrivateA() { RequireJS / Javascript TypeScript function DoThePrivateA() { return '(aaaa)'; CommonJS return '(aaaa)'; } } }) ModuleB.ts define(["require", "exports", 'ModuleA'], function(require, exports, __a__) { import a = module('ModuleA'); var a = __a__; export function DoTheBA() { function DoTheBA() { return 'BBBB' + a.DoTheA(); return 'BBBB' + a.DoTheA(); } } exports.DoTheBA = DoTheBA; })
  • 12. Lambdas TypeScript this._participants.forEach(p => this.invite(p)); this._participants.forEach(p => this.invite(p)); Javascript var _this = this; this._participants.forEach(function (p) { return _this.invite(p); })
  • 13. Una library en JS: external.js AnUglyGlobal = function (value) { JS Libraries this.field = value; } // a constructor AnUglyGlobal.prototype.doIt = function(x) { return this.field + x; DefinitelyTyped } // a method define los tipos de más de 130 libraries La declaración de la library para TS: external.d.ts interface UglyGlobal { Angular, underscore, field: string; Jquery, ember, doIt(value: string); Knockout, etc.. } https://github.com/borisyank declare var AnUglyGlobal : UglyGlobal; ov/DefinitelyTyped El código TS que usa la library: uses_external.ts /// <reference path="external.d.ts"/> AnUglyGlobal.doIt("foo");
  • 14. Muy lindo, pero ya existe… • CoffeeScript o No es JS. No hay type checking. • Closure o Anotaciones en la documentación. Algo más ‘verboso’. Optimizador. • Traceur o Diseñado para experimentar con construcciones futuras de ES. o No hay type checking. o Pocas consideraciones sobre el código generado • Dart o Require un runtime, más ambicioso y menos JS.
  • 15. Type Checking? Douglas Crockford: Microsoft's TypeScript may be the best of the many JavaScript front ends. (…) it seems to generate the most attractive code. (…) it should take pressure off of the ECMAScript Standard for new features like type declarations and classes. (…) these can be provided nicely by a preprocessor, so there is no need to change the underlying language. I think that JavaScript's loose typing is one of its best features and that type checking is way overrated. TypeScript adds sweetness, but at a price. It is not a price I am willing to pay.
  • 16. Por qué lo elegimos? • Implementado un diseño OO existente. • No queríamos tener que inventar nuestra propia forma de definir clases, herencia, o de definición de módulos. • Dispuestos a aceptar mejoras sobre JS poco intrusivas (opt-out), que se integren bien con nuestro entorno actual. • No queríamos que todo el equipo aprendiera un nuevo lenguaje, preferíamos algo familiar. • Type Checking :)
  • 17. Links • TypeScript source code (http://typescript.codeplex.com/) • TypeScript Playground (http://www.typescriptlang.org/Playground/) • Ace editor (http://ace.ajax.org/, https://github.com/hi104/typescript- playground-on-ace) • CofeeScript: http://coffeescript.org/ • Closure: https://developers.google.com/closure/compiler/ • Traceur: https://code.google.com/p/traceur-compiler/, http://traceur- compiler.googlecode.com/git/demo/repl.html • Me: saguiar@infragistics.com

Notas del editor

  1. Presentaremoslasprincipalescaracterísticas de TypeScript, quecosasnuevastrae al mundo de Javascript, mostraremosconstrucciones y sintaxis del lenguaje y luegodiscutiremossuutilidadcomoherramientapara el desarrollo de aplicaciones web.