SlideShare a Scribd company logo
TypeScript
Lukas Gamper
Demian Holderegger
uSystems GmbH
Agenda
TypeScript: Die Sprache
TypeScript in der Praxis
Wie ist TypeScript
entstanden?
- 2011 Entwicklung von ES6 beginnt
- 2012 Microsoft entwickelt TypeScript
- 2015 Angular2 mit TypeScript
Einsatz von TypeScript
TypeScript:
die Sprache
Was ist TypeScript?
- Kompiliert nach JavaScript
- Generiert lesbaren JS Code
Was ist TypeScript?
- Superset von ES6
- Unterstützt Typen
ES6 Support
Vorteile von Typescipt
- Keine Typenfehler mit Strong Typing
- ES6 kann schon jetzt benutzt werden:
- Besser strukturiert mit Klassen
- Viele Sprachverbesserungen wie
let, for … of, ()=>..., etc.
- Boolean, Number, String
- Array, Tuple
- Enum
- Function
- Object
- Void
- Any
Statische Typen
var isDone: boolean = false;
Boolean
var height: number = 6;
Number
var name: string = "bob";
name = 'smith';
String
var list:number[] = [1, 2, 3];
var list:Array<number> = [1, 2, 3];
Array
var tuple:[number, string]
= [1, "bob"];
var secondElement:string
= tuple[1];
Tuple
enum Color {Red, Green, Blue=4};
var c: Color = Color.Green;
Enum
var cb:(name:string):string =
function(name:string):string {
return ‘Hello ’ + Bob;
}
console.log(cb(‘Bob’)) // Hello Bob
Function
var square:{color:string; area:number}
= {color: white, area: 100}
Object
function warnUser(): void {
alert("This is my warning message");
}
Void
var notSure: any = 4;
var unknown = ‘foo’;
Any
Klassen
TypeScript
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet(): string {
return "Hello, " + this.greeting;
}
}
var greeter = new Greeter("world");
JavaScript
function Greeter(message) {
this.greeting = message;
}
Greeter.prototype.greet = function() {
return "Hello, " + this.greeting;
}
var greeter = new Greeter("world");
Private / Public
class Greeter {
private greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
var greeter = new Greeter("world");
class Greeter {
constructor(private greeting: string) {}
greet() {
return "Hello, " + this.greeting;
}
}
var greeter = new Greeter("world");
class Animal {
constructor(public name: string) {}
move(meters: number = 0):void {
alert( this.name + ": " + meters);
}
}
class Snake extends Animal {
constructor(name: string) {
super(name);
}
move(meters: number = 5):void {
alert("Slithering...");
super.move(meters);
}
}
Vererbung
class Horse extends Animal {
constructor(name: string) {
super(name);
}
move(meters: number = 45):void {
alert("Galloping...");
super.move(meters);
}
}
Interfaces
interface AnimalInterface {
name:string;
constructor(theName: string);
move(meters: number) ;
}
interface ReptileInterface {}
interface SnakeInterface
extends AnimalInterface, R eptileIn
{
constructor(name: string)
move(meters: number);
}
class Animal implements AnimalInterface {
constructor(public name: string) {}
move(meters: number = 0) {
alert( this.name + " moved " +
meters + "m.");
}
}
class Snake extends Animal implements
SnakeInterface, R eptileInterface {
constructor(name: string) { super
(name); }
move(meters: number = 5) {
alert("Slithering...");
super.move(meters);
}
}
Arrow Functions ()=>...
- kein function keyword
- kein Scope
- this von outer scope vererbt
- arguments bleibt unverändert
- bind hat keine Wikrung
Arrow Functions ()=>...
mit brackets
var inc = (arg: number):number => {
return a + 1
}
ohne brackets
var inc = (a)=>a+1
JavaScript
var inc = function(arg:number):number {
return a + 1
}
Arrow Functions ()=>...
JavaScript
function Person(age) {
this.age = age
this.growOld = (function(){
++this.age;
}).bind(this);
}
let person = new Person(1);
person.growOld()
TypeScript
function Person(age) {
this.age = age
this.growOld = ():void=>{
++this.age;
}
}
let person = new Person(1);
person.growOld()
let
▪ Variablen in ES5 sind function scoped
▪ Let definiert block scoped Variablen
▪ Zugriff auf let Variablen vor ihrer
definition wirft ReferenceError
let
JavaScript
var foo = 123;
if (true) {
var foo = 456;
}
console.log(foo); // 456
TypeScript
let foo = 123;
if (true) {
let foo = 456;
}
console.log(foo); // 123
let
JavaScript
var vals = [];
for (var x = 0; x < 4; ++x)
vals.push(()=>x);
console.log(vals.map(cb=>cb()));
// [4, 4, 4, 4]
typeScript
let vals = [];
for (let x = 0; x < 4; ++x)
vals.push(()=>x);
console.log(vals.map(cb=>cb()));
// [0, 1, 2, 3]
String Templates - Multiline String
JavaScript
var lyrics = "Never gonna give you up 
nNever gonna let you down";
TypeScript
var lyrics = `Never gonna give you up
Never gonna let you down`;
String Templates - String Interpolation
JavaScript
var lyrics = 'Never gonna give you up';
var a = '<div>' + lyrics + '</div>';
var b = ‘1 and 1 one make ' + (1 + 1)
TypeScript
var lyrics = 'Never gonna give you up';
var a = `<div>${lyrics}</div>`;
var b = `1 and 1 one make ${1 + 1}`
for … of
var someArray = [9, 2, 5];
for (var item in someArray) {
console.log(item); // 0,1,2
}
var someArray = [9, 2, 5];
for (var item of someArray) {
console.log(item); // 9,2,5
}
Beispiel: Grid von vuejs.org
/// <reference path="vue-component.ts" />
@createComponent('demo-grid')
class DemoGrid extends ComponentBase {
static template:string = '#grid-template';
@prop({ type: Array, required: true })
data:Array<{name: string, power:number }>;
@prop({ type: Array, required: true })
columns:Array< string>;
sortKey:string = '';
reversed:{[key: string]: boolean} = {};
@hook('compiled')
compiled(): void {
this.columns.forEach((key: string):void => {
this.$set(`reversed.${key}`, false);
});
}
sortBy(key: string):void {
this.sortKey = key;
this.reversed[key] = ! this.reversed[key];
}
}
Vue.component('demo-grid', {
template: '#grid-template',
props: {
data: {type:Array, required: true},
columns: {type:Array, required:
true}
},
data: function () {
return {
data: null,
columns: null,
sortKey: '',
rev: {}
};
},
compiled: function () {
var self = this;
this.columns.forEach( function (key)
{
self.$set(rev.' + key, false);
});
},
methods: {
sortBy: function (key) {
this.sortKey = key;
this.rev[key] = ! this.rev[key];
}
}
});
/// <reference path="vue-component.ts" />
@createComponent('demo-grid')
class DemoGrid extends ComponentBase {
static template:string = '#grid-template';
@prop({ type: Array, required: true })
data:Array<{name: string, power:number }>;
@prop({ type: Array, required: true })
columns:Array< string>;
sortKey:string = '';
reversed:{[key: string]: boolean} = {};
@hook('compiled')
compiled(): void {
this.columns.forEach((key: string):void => {
this.$set(`reversed.${key}`, false);
});
}
sortBy(key: string):void {
this.sortKey = key;
this.reversed[key] = ! this.reversed[key];
}
}
Vue.component('demo-grid', {
template: '#grid-template',
props: {
data: {type:Array, required: true},
columns: {type:Array, required:
true}
},
data: function () {
return {
data: null,
columns: null,
sortKey: '',
rev: {}
};
},
compiled: function () {
var self = this;
this.columns.forEach( function (key)
{
self.$set(rev.' + key, false);
});
},
methods: {
sortBy: function (key) {
this.sortKey = key;
this.rev[key] = ! this.rev[key];
}
}
});
Decorators / Annotations
/// <reference path="vue-component.ts" />
@createComponent('demo-grid')
class DemoGrid extends ComponentBase {
static template:string = '#grid-template';
@prop({ type: Array, required: true })
data:Array<{name: string, power:number }>;
@prop({ type: Array, required: true })
columns:Array< string>;
sortKey:string = '';
reversed:{[key: string]: boolean} = {};
@hook('compiled')
compiled(): void {
this.columns.forEach((key: string):void => {
this.$set(`reversed.${key}`, false);
});
}
sortBy(key: string):void {
this.sortKey = key;
this.reversed[key] = ! this.reversed[key];
}
}
Vue.component('demo-grid', {
template: '#grid-template',
props: {
data: {type:Array, required: true},
columns: {type:Array, required:
true}
},
data: function () {
return {
data: null,
columns: null,
sortKey: '',
rev: {}
};
},
compiled: function () {
var self = this;
this.columns.forEach( function (key)
{
self.$set(rev.' + key, false);
});
},
methods: {
sortBy: function (key) {
this.sortKey = key;
this.rev[key] = ! this.rev[key];
}
}
});
Klassen und Typen
/// <reference path="vue-component.ts" />
@createComponent('demo-grid')
class DemoGrid extends ComponentBase {
static template:string = '#grid-template';
@prop({ type: Array, required: true })
data:Array<{name: string, power:number }>;
@prop({ type: Array, required: true })
columns:Array< string>;
sortKey:string = '';
reversed:{[key: string]: boolean} = {};
@hook('compiled')
compiled(): void {
this.columns.forEach((key: string):void => {
this.$set(`reversed.${key}`, false);
});
}
sortBy(key: string):void {
this.sortKey = key;
this.reversed[key] = ! this.reversed[key];
}
}
Vue.component('demo-grid', {
template: '#grid-template',
props: {
data: {type:Array, required: true},
columns: {type:Array, required:
true}
},
data: function () {
return {
data: null,
columns: null,
sortKey: '',
rev: {}
};
},
compiled: function () {
var self = this;
this.columns.forEach( function (key)
{
self.$set(rev.' + key, false);
});
},
methods: {
sortBy: function (key) {
this.sortKey = key;
this.rev[key] = ! this.rev[key];
}
}
});
Arrow Functions
/// <reference path="vue-component.ts" />
@createComponent('demo-grid')
class DemoGrid extends ComponentBase {
static template:string = '#grid-template';
@prop({ type: Array, required: true })
data:Array<{name: string, power:number }>;
@prop({ type: Array, required: true })
columns:Array< string>;
sortKey:string = '';
reversed:{[key: string]: boolean} = {};
@hook('compiled')
compiled(): void {
this.columns.forEach((key: string):void => {
this.$set(`reversed.${key}`, false);
});
}
sortBy(key: string):void {
this.sortKey = key;
this.reversed[key] = ! this.reversed[key];
}
}
Vue.component('demo-grid', {
template: '#grid-template',
props: {
data: {type:Array, required: true},
columns: {type:Array, required:
true}
},
data: function () {
return {
data: null,
columns: null,
sortKey: '',
rev: {}
};
},
compiled: function () {
var self = this;
this.columns.forEach( function (key)
{
self.$set(rev.' + key, false);
});
},
methods: {
sortBy: function (key) {
this.sortKey = key;
this.rev[key] = ! this.rev[key];
}
}
});
String Template
Vorteile
TypeScript in
der Praxis
Native Unterstützung in
PHPStorm 9
Native Unterstützung in PhpStorm 9
Debugging
Debugging im Chrome
Breakpoints
source map files
Einbinden in bestehenden
Code
JavaScript ist TypeScript!
DefinitelyTyped
Interface Dateien für bestehende Libraries
http://definitelytyped.org/
DefinitelyTyped
▪ GitHub Repo mit über 1000 *.d.ts
Dateien von bekannten Libraries
▪ Einfach selber zu schreiben: es sind
nur Interfaces
DefinitelyTyped
Beispiel: jQuery
$(“.myclass”); // Liste der Elemente
declare var $: JQuery;
interface JQuery {
(selector: string): JQueryObject;
...
}
DefinitelyTyped
Beispiel: AngularJS $http Service
interface IHttpService {
post<T>(
url: string,
data: any,
config?: IRequestShortcutConfig
): IHttpPromise<T>;
...
}
DefinitelyTyped
Yet Another Package Manager: tsd
▪ ähnlich wie Bower
▪ erstellt Reference Datei mit allen
includes
▪ Manifest Datei: tsd.json
Testing
▪ Grundsätzlich gleich wie mit
JavaScript
▪ Tests in TypeScript schreiben (.d.ts)
▪ tsUnit
Ausblick
- generators (1.6)
- await / async (2.0)
Pro
▪ weniger Fehler
▪ schönerer Code
▪ schnellere Entwicklung
▪ Modularisierung
Cons
▪ .d.ts Dateien teilweise veraltet
▪ Dokumentation nicht up to date
▪ Muss immer kompiliert werden
Thank you!
www.usystems.ch
function *g(limit) {
for (var i = 0; i < limit; i++) {
yield i;
}
}
for (let i of g(100)) {
console.log(i);
}
var array = [...g(50)];
var [first, second, ...rest] = g(100);
Backup: generators
async myFunction(): Promise<any> {
var result = await loadAjaxData();
return result;
}
Backup: await / async
function foo(x) {
while (true) {
x = x * 2;
yield x;
}
}
var g = foo(2);
g.next(); // -> 4
g.next(); // -> 8
g.next(); // -> 16
Backup: yield
Ressourcen
Offizielle Seite:
www.typescriptlang.org
Offizielle Referenz:
www.typescriptlang.org/Handbook
Gibbook
basarat.gitbooks.io/typescript/content/

More Related Content

What's hot (20)

PDF
Proxies are Awesome!
Brendan Eich
 
PDF
Haskell in the Real World
osfameron
 
PDF
PHP Language Trivia
Nikita Popov
 
PPTX
Java script arrays
Frayosh Wadia
 
PDF
LetSwift RxSwift 시작하기
Wanbok Choi
 
KEY
Google Guava
Alexander Korotkikh
 
PDF
Google Guava - Core libraries for Java & Android
Jordi Gerona
 
DOCX
What are arrays in java script
Miguel Silva Loureiro
 
PDF
Introduction to Scala for Java Developers
Michael Galpin
 
PDF
Developer Experience i TypeScript. Najbardziej ikoniczne duo
The Software House
 
PDF
CoffeeScript
None
 
PDF
Scala for Java programmers
輝 子安
 
PDF
Introduction to Scala for JCConf Taiwan
Jimin Hsieh
 
PPT
JavaScript Arrays
Reem Alattas
 
PPT
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 
PDF
Design Patterns - Compiler Case Study - Hands-on Examples
Ganesh Samarthyam
 
PDF
Swift, functional programming, and the future of Objective-C
Alexis Gallagher
 
PDF
Scala 2013 review
Sagie Davidovich
 
PDF
ES6 - Next Generation Javascript
RameshNair6
 
PDF
Google guava overview
Steve Min
 
Proxies are Awesome!
Brendan Eich
 
Haskell in the Real World
osfameron
 
PHP Language Trivia
Nikita Popov
 
Java script arrays
Frayosh Wadia
 
LetSwift RxSwift 시작하기
Wanbok Choi
 
Google Guava
Alexander Korotkikh
 
Google Guava - Core libraries for Java & Android
Jordi Gerona
 
What are arrays in java script
Miguel Silva Loureiro
 
Introduction to Scala for Java Developers
Michael Galpin
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
The Software House
 
CoffeeScript
None
 
Scala for Java programmers
輝 子安
 
Introduction to Scala for JCConf Taiwan
Jimin Hsieh
 
JavaScript Arrays
Reem Alattas
 
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 
Design Patterns - Compiler Case Study - Hands-on Examples
Ganesh Samarthyam
 
Swift, functional programming, and the future of Objective-C
Alexis Gallagher
 
Scala 2013 review
Sagie Davidovich
 
ES6 - Next Generation Javascript
RameshNair6
 
Google guava overview
Steve Min
 

Similar to Einführung in TypeScript (10)

PDF
29. Treffen - Tobias Meier - TypeScript
.NET User Group Rhein-Neckar
 
PPTX
What's New in TypeScript
Microsoft Tech Community
 
PPTX
Type script, for dummies
santiagoaguiar
 
PPTX
Angular2 for Beginners
Oswald Campesato
 
PDF
Typowanie nominalne w TypeScript
The Software House
 
PPTX
TypeScript
Oswald Campesato
 
PPTX
Why TypeScript?
FITC
 
PDF
TypeScript Introduction
Hans Höchtl
 
KEY
Coffee Scriptでenchant.js
Naoyuki Totani
 
PDF
TypeScript Best Practices
felixbillon
 
29. Treffen - Tobias Meier - TypeScript
.NET User Group Rhein-Neckar
 
What's New in TypeScript
Microsoft Tech Community
 
Type script, for dummies
santiagoaguiar
 
Angular2 for Beginners
Oswald Campesato
 
Typowanie nominalne w TypeScript
The Software House
 
TypeScript
Oswald Campesato
 
Why TypeScript?
FITC
 
TypeScript Introduction
Hans Höchtl
 
Coffee Scriptでenchant.js
Naoyuki Totani
 
TypeScript Best Practices
felixbillon
 
Ad

Recently uploaded (20)

PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Ad

Einführung in TypeScript

  • 3. Wie ist TypeScript entstanden? - 2011 Entwicklung von ES6 beginnt - 2012 Microsoft entwickelt TypeScript - 2015 Angular2 mit TypeScript
  • 6. Was ist TypeScript? - Kompiliert nach JavaScript - Generiert lesbaren JS Code
  • 7. Was ist TypeScript? - Superset von ES6 - Unterstützt Typen
  • 9. Vorteile von Typescipt - Keine Typenfehler mit Strong Typing - ES6 kann schon jetzt benutzt werden: - Besser strukturiert mit Klassen - Viele Sprachverbesserungen wie let, for … of, ()=>..., etc.
  • 10. - Boolean, Number, String - Array, Tuple - Enum - Function - Object - Void - Any Statische Typen
  • 11. var isDone: boolean = false; Boolean
  • 12. var height: number = 6; Number
  • 13. var name: string = "bob"; name = 'smith'; String
  • 14. var list:number[] = [1, 2, 3]; var list:Array<number> = [1, 2, 3]; Array
  • 15. var tuple:[number, string] = [1, "bob"]; var secondElement:string = tuple[1]; Tuple
  • 16. enum Color {Red, Green, Blue=4}; var c: Color = Color.Green; Enum
  • 17. var cb:(name:string):string = function(name:string):string { return ‘Hello ’ + Bob; } console.log(cb(‘Bob’)) // Hello Bob Function
  • 18. var square:{color:string; area:number} = {color: white, area: 100} Object
  • 19. function warnUser(): void { alert("This is my warning message"); } Void
  • 20. var notSure: any = 4; var unknown = ‘foo’; Any
  • 21. Klassen TypeScript class Greeter { greeting: string; constructor(message: string) { this.greeting = message; } greet(): string { return "Hello, " + this.greeting; } } var greeter = new Greeter("world"); JavaScript function Greeter(message) { this.greeting = message; } Greeter.prototype.greet = function() { return "Hello, " + this.greeting; } var greeter = new Greeter("world");
  • 22. Private / Public class Greeter { private greeting: string; constructor(message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } } var greeter = new Greeter("world"); class Greeter { constructor(private greeting: string) {} greet() { return "Hello, " + this.greeting; } } var greeter = new Greeter("world");
  • 23. class Animal { constructor(public name: string) {} move(meters: number = 0):void { alert( this.name + ": " + meters); } } class Snake extends Animal { constructor(name: string) { super(name); } move(meters: number = 5):void { alert("Slithering..."); super.move(meters); } } Vererbung class Horse extends Animal { constructor(name: string) { super(name); } move(meters: number = 45):void { alert("Galloping..."); super.move(meters); } }
  • 24. Interfaces interface AnimalInterface { name:string; constructor(theName: string); move(meters: number) ; } interface ReptileInterface {} interface SnakeInterface extends AnimalInterface, R eptileIn { constructor(name: string) move(meters: number); } class Animal implements AnimalInterface { constructor(public name: string) {} move(meters: number = 0) { alert( this.name + " moved " + meters + "m."); } } class Snake extends Animal implements SnakeInterface, R eptileInterface { constructor(name: string) { super (name); } move(meters: number = 5) { alert("Slithering..."); super.move(meters); } }
  • 25. Arrow Functions ()=>... - kein function keyword - kein Scope - this von outer scope vererbt - arguments bleibt unverändert - bind hat keine Wikrung
  • 26. Arrow Functions ()=>... mit brackets var inc = (arg: number):number => { return a + 1 } ohne brackets var inc = (a)=>a+1 JavaScript var inc = function(arg:number):number { return a + 1 }
  • 27. Arrow Functions ()=>... JavaScript function Person(age) { this.age = age this.growOld = (function(){ ++this.age; }).bind(this); } let person = new Person(1); person.growOld() TypeScript function Person(age) { this.age = age this.growOld = ():void=>{ ++this.age; } } let person = new Person(1); person.growOld()
  • 28. let ▪ Variablen in ES5 sind function scoped ▪ Let definiert block scoped Variablen ▪ Zugriff auf let Variablen vor ihrer definition wirft ReferenceError
  • 29. let JavaScript var foo = 123; if (true) { var foo = 456; } console.log(foo); // 456 TypeScript let foo = 123; if (true) { let foo = 456; } console.log(foo); // 123
  • 30. let JavaScript var vals = []; for (var x = 0; x < 4; ++x) vals.push(()=>x); console.log(vals.map(cb=>cb())); // [4, 4, 4, 4] typeScript let vals = []; for (let x = 0; x < 4; ++x) vals.push(()=>x); console.log(vals.map(cb=>cb())); // [0, 1, 2, 3]
  • 31. String Templates - Multiline String JavaScript var lyrics = "Never gonna give you up nNever gonna let you down"; TypeScript var lyrics = `Never gonna give you up Never gonna let you down`;
  • 32. String Templates - String Interpolation JavaScript var lyrics = 'Never gonna give you up'; var a = '<div>' + lyrics + '</div>'; var b = ‘1 and 1 one make ' + (1 + 1) TypeScript var lyrics = 'Never gonna give you up'; var a = `<div>${lyrics}</div>`; var b = `1 and 1 one make ${1 + 1}`
  • 33. for … of var someArray = [9, 2, 5]; for (var item in someArray) { console.log(item); // 0,1,2 } var someArray = [9, 2, 5]; for (var item of someArray) { console.log(item); // 9,2,5 }
  • 34. Beispiel: Grid von vuejs.org
  • 35. /// <reference path="vue-component.ts" /> @createComponent('demo-grid') class DemoGrid extends ComponentBase { static template:string = '#grid-template'; @prop({ type: Array, required: true }) data:Array<{name: string, power:number }>; @prop({ type: Array, required: true }) columns:Array< string>; sortKey:string = ''; reversed:{[key: string]: boolean} = {}; @hook('compiled') compiled(): void { this.columns.forEach((key: string):void => { this.$set(`reversed.${key}`, false); }); } sortBy(key: string):void { this.sortKey = key; this.reversed[key] = ! this.reversed[key]; } } Vue.component('demo-grid', { template: '#grid-template', props: { data: {type:Array, required: true}, columns: {type:Array, required: true} }, data: function () { return { data: null, columns: null, sortKey: '', rev: {} }; }, compiled: function () { var self = this; this.columns.forEach( function (key) { self.$set(rev.' + key, false); }); }, methods: { sortBy: function (key) { this.sortKey = key; this.rev[key] = ! this.rev[key]; } } });
  • 36. /// <reference path="vue-component.ts" /> @createComponent('demo-grid') class DemoGrid extends ComponentBase { static template:string = '#grid-template'; @prop({ type: Array, required: true }) data:Array<{name: string, power:number }>; @prop({ type: Array, required: true }) columns:Array< string>; sortKey:string = ''; reversed:{[key: string]: boolean} = {}; @hook('compiled') compiled(): void { this.columns.forEach((key: string):void => { this.$set(`reversed.${key}`, false); }); } sortBy(key: string):void { this.sortKey = key; this.reversed[key] = ! this.reversed[key]; } } Vue.component('demo-grid', { template: '#grid-template', props: { data: {type:Array, required: true}, columns: {type:Array, required: true} }, data: function () { return { data: null, columns: null, sortKey: '', rev: {} }; }, compiled: function () { var self = this; this.columns.forEach( function (key) { self.$set(rev.' + key, false); }); }, methods: { sortBy: function (key) { this.sortKey = key; this.rev[key] = ! this.rev[key]; } } }); Decorators / Annotations
  • 37. /// <reference path="vue-component.ts" /> @createComponent('demo-grid') class DemoGrid extends ComponentBase { static template:string = '#grid-template'; @prop({ type: Array, required: true }) data:Array<{name: string, power:number }>; @prop({ type: Array, required: true }) columns:Array< string>; sortKey:string = ''; reversed:{[key: string]: boolean} = {}; @hook('compiled') compiled(): void { this.columns.forEach((key: string):void => { this.$set(`reversed.${key}`, false); }); } sortBy(key: string):void { this.sortKey = key; this.reversed[key] = ! this.reversed[key]; } } Vue.component('demo-grid', { template: '#grid-template', props: { data: {type:Array, required: true}, columns: {type:Array, required: true} }, data: function () { return { data: null, columns: null, sortKey: '', rev: {} }; }, compiled: function () { var self = this; this.columns.forEach( function (key) { self.$set(rev.' + key, false); }); }, methods: { sortBy: function (key) { this.sortKey = key; this.rev[key] = ! this.rev[key]; } } }); Klassen und Typen
  • 38. /// <reference path="vue-component.ts" /> @createComponent('demo-grid') class DemoGrid extends ComponentBase { static template:string = '#grid-template'; @prop({ type: Array, required: true }) data:Array<{name: string, power:number }>; @prop({ type: Array, required: true }) columns:Array< string>; sortKey:string = ''; reversed:{[key: string]: boolean} = {}; @hook('compiled') compiled(): void { this.columns.forEach((key: string):void => { this.$set(`reversed.${key}`, false); }); } sortBy(key: string):void { this.sortKey = key; this.reversed[key] = ! this.reversed[key]; } } Vue.component('demo-grid', { template: '#grid-template', props: { data: {type:Array, required: true}, columns: {type:Array, required: true} }, data: function () { return { data: null, columns: null, sortKey: '', rev: {} }; }, compiled: function () { var self = this; this.columns.forEach( function (key) { self.$set(rev.' + key, false); }); }, methods: { sortBy: function (key) { this.sortKey = key; this.rev[key] = ! this.rev[key]; } } }); Arrow Functions
  • 39. /// <reference path="vue-component.ts" /> @createComponent('demo-grid') class DemoGrid extends ComponentBase { static template:string = '#grid-template'; @prop({ type: Array, required: true }) data:Array<{name: string, power:number }>; @prop({ type: Array, required: true }) columns:Array< string>; sortKey:string = ''; reversed:{[key: string]: boolean} = {}; @hook('compiled') compiled(): void { this.columns.forEach((key: string):void => { this.$set(`reversed.${key}`, false); }); } sortBy(key: string):void { this.sortKey = key; this.reversed[key] = ! this.reversed[key]; } } Vue.component('demo-grid', { template: '#grid-template', props: { data: {type:Array, required: true}, columns: {type:Array, required: true} }, data: function () { return { data: null, columns: null, sortKey: '', rev: {} }; }, compiled: function () { var self = this; this.columns.forEach( function (key) { self.$set(rev.' + key, false); }); }, methods: { sortBy: function (key) { this.sortKey = key; this.rev[key] = ! this.rev[key]; } } }); String Template
  • 42. Native Unterstützung in PHPStorm 9 Native Unterstützung in PhpStorm 9
  • 45. DefinitelyTyped Interface Dateien für bestehende Libraries http://definitelytyped.org/
  • 46. DefinitelyTyped ▪ GitHub Repo mit über 1000 *.d.ts Dateien von bekannten Libraries ▪ Einfach selber zu schreiben: es sind nur Interfaces
  • 47. DefinitelyTyped Beispiel: jQuery $(“.myclass”); // Liste der Elemente declare var $: JQuery; interface JQuery { (selector: string): JQueryObject; ... }
  • 48. DefinitelyTyped Beispiel: AngularJS $http Service interface IHttpService { post<T>( url: string, data: any, config?: IRequestShortcutConfig ): IHttpPromise<T>; ... }
  • 49. DefinitelyTyped Yet Another Package Manager: tsd ▪ ähnlich wie Bower ▪ erstellt Reference Datei mit allen includes ▪ Manifest Datei: tsd.json
  • 50. Testing ▪ Grundsätzlich gleich wie mit JavaScript ▪ Tests in TypeScript schreiben (.d.ts) ▪ tsUnit
  • 51. Ausblick - generators (1.6) - await / async (2.0)
  • 52. Pro ▪ weniger Fehler ▪ schönerer Code ▪ schnellere Entwicklung ▪ Modularisierung
  • 53. Cons ▪ .d.ts Dateien teilweise veraltet ▪ Dokumentation nicht up to date ▪ Muss immer kompiliert werden
  • 55. function *g(limit) { for (var i = 0; i < limit; i++) { yield i; } } for (let i of g(100)) { console.log(i); } var array = [...g(50)]; var [first, second, ...rest] = g(100); Backup: generators
  • 56. async myFunction(): Promise<any> { var result = await loadAjaxData(); return result; } Backup: await / async
  • 57. function foo(x) { while (true) { x = x * 2; yield x; } } var g = foo(2); g.next(); // -> 4 g.next(); // -> 8 g.next(); // -> 16 Backup: yield