TypeScript is a language and compiler that generates JavaScript. It was developed by Microsoft and designed by Anders Hejlsberg to add type safety to JavaScript. TypeScript adds features like classes, interfaces, modules and type checking to JavaScript to help catch errors earlier. The TypeScript compiler and language services are written in TypeScript itself, making it cross-platform. TypeScript compiles to standard JavaScript and can be used in any environment that supports JavaScript.
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;
})
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 :)
Presentaremoslasprincipalescaracterísticas de TypeScript, quecosasnuevastrae al mundo de Javascript, mostraremosconstrucciones y sintaxis del lenguaje y luegodiscutiremossuutilidadcomoherramientapara el desarrollo de aplicaciones web.