SlideShare a Scribd company logo
1 of 58
Download to read offline
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

CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
None
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
Sagie Davidovich
 

What's hot (20)

Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
 
Haskell in the Real World
Haskell in the Real WorldHaskell in the Real World
Haskell in the Real World
 
PHP Language Trivia
PHP Language TriviaPHP Language Trivia
PHP Language Trivia
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
 
LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & Android
 
What are arrays in java script
What are arrays in java scriptWhat are arrays in java script
What are arrays in java script
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java Developers
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
Scala for Java programmers
Scala for Java programmersScala for Java programmers
Scala for Java programmers
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
 
JavaScript Arrays
JavaScript Arrays JavaScript Arrays
JavaScript Arrays
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-C
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Google guava overview
Google guava overviewGoogle guava overview
Google guava overview
 

Similar to Einführung in TypeScript

Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scala
parag978978
 

Similar to Einführung in TypeScript (20)

Scala introduction
Scala introductionScala introduction
Scala introduction
 
Typescript - why it's awesome
Typescript - why it's awesomeTypescript - why it's awesome
Typescript - why it's awesome
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
 
A la découverte de TypeScript
A la découverte de TypeScriptA la découverte de TypeScript
A la découverte de TypeScript
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Groovy
GroovyGroovy
Groovy
 
C to perl binding
C to perl bindingC to perl binding
C to perl binding
 
Charla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo WebCharla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo Web
 
Rits Brown Bag - TypeScript
Rits Brown Bag - TypeScriptRits Brown Bag - TypeScript
Rits Brown Bag - TypeScript
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
Introduction to TypeScript
Introduction to TypeScriptIntroduction to TypeScript
Introduction to TypeScript
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scala
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Recently uploaded (20)

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
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
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 

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