Upgrade to Pro — share decks privately, control downloads, hide ads and more …

TypeScript, for dummies?

TypeScript, for dummies?

Presentación sobre TypeScript para la JSMeetup del 2013-4-4 (http://www.meetup.com/mvd-js/events/103587282/)

Santiago Aguiar

April 05, 2013
Tweet

More Decks by Santiago Aguiar

Other Decks in Technology

Transcript

  1. ¿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/
  2. Qué aporta….? • Superset de JavaScript o Todo código JS

    es código TS válido • Compile-time type checking, opcional • Construcciones de ECMAScript 6: o Módulos o Clases y OOP o Lambdas o No mucho más… • Tooling: completion, refactoring, navigation. ...casi ...casi
  3. 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
  4. 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
  5. var name: string; name = 0; name = "foo"; var

    point: { x: number; y: number; z?: number; }; 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; Tipos
  6. class User { constructor(public name: string) { } } class

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

    constructor(date?: Date) { this._date = date || new Date(); } 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!'); } } Miembros
  8. 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); Interfaces & Structural Typing
  9. Módulos export function DoTheA() { return 'AAAA!'; } function DoThePrivateA()

    { return '(aaaa)'; } import a = module('ModuleA'); export function DoTheBA() { return 'BBBB' + a.DoTheA(); } ModuleA.ts ModuleB.ts define(["require", "exports"], function(require, exports) { function DoTheA() { return 'AAAA!'; } exports.DoTheA = DoTheA; function DoThePrivateA() { return '(aaaa)'; } }) define(["require", "exports", 'ModuleA'], function(require, exports, __a__) { var a = __a__; function DoTheBA() { return 'BBBB' + a.DoTheA(); } exports.DoTheBA = DoTheBA; }) TypeScript Javascript Implementado por RequireJS / CommonJS
  10. Lambdas this._participants.forEach(p => this.invite(p)); this._participants.forEach(p => this.invite(p)); var _this =

    this; this._participants.forEach(function (p) { return _this.invite(p); }) TypeScript Javascript
  11. AnUglyGlobal = function (value) { this.field = value; } //

    a constructor AnUglyGlobal.prototype.doIt = function(x) { return this.field + x; } // a method JS Libraries interface UglyGlobal { field: string; doIt(value: string); } declare var AnUglyGlobal : UglyGlobal; /// <reference path="external.d.ts"/> AnUglyGlobal.doIt("foo"); Una library en JS: external.js La declaración de la library para TS: external.d.ts El código TS que usa la library: uses_external.ts DefinitelyTyped define los tipos de más de 130 libraries Angular, underscore, Jquery, ember, Knockout, etc.. https://github.com/borisyank ov/DefinitelyTyped
  12. 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.
  13. Type Checking? 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. Douglas Crockford:
  14. 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 :)
  15. 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: [email protected]