SlideShare ist ein Scribd-Unternehmen logo
1 von 36
Downloaden Sie, um offline zu lesen
TypeScript
Hans Höchtl
Technical Director @ Onedrop
PHP, Java, Ruby Developer
TYPO3 Solr, Neos
Back in time to the beginning of
JavaScript
• Developed in 10 days back in 1995
• Target: Easy script interaction for hobby
programmers in the browser, who can’t write
Java
• 1996 handed over to ECMA for standardization
• ECMAScript 5 (spec. 1999) supported by all
browsers (>=IE9)
JavaScript - What happened?
• CoffeeScript
• Modularization (requireJS, AMD, etc.)
• jQuery
• NodeJS
JavaScript - In the enterprise?
• Not typesafe
• No objects/classes
• Hard to test
• Bad Async handling
TypeScript to the rescue
• Released 2012 by Microsoft
• Developed by Anders Hejlsberg (C#, Delphi)
• Compiles to JavaScript (configurable version)
• Full OOP
• Type-safe
• JavaScript compatible
ES5

JavaScript 1.5
ES2015 (ES6) TypeScript
Buzzword bingo
Types
var / let / const
Inheritance
Promises
Generics
Fat arrow
Interfaces
Decorators
public / private
Moduls
Class
Typing
var foo: string = 'bar';
var bar: any = ['lorem', 2];
function (p: Person) {
console.log(p.lastName);
}
function getAddress(): Address {
return this.address;
}
function getCountAndObject(): [number, any] {
return [this.addresses.length, this.addresses];
}
Types
// Primitives
var foo: string = 'bar';
var bar: any = ['lorem', 2];
// Arrays
var listOfSomething: number[] = [1,2,3];
var listOfSomething: Array<number> = [1,2,3];
// Tuples
var tuple: [string, number] = ['Hello', 5];
// Enum
enum Color {Red, Green, Blue};
var c: Color = Color.Green;
// Casting
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
// Literals
type Easing = "ease-in" | "ease-out" | "ease-in-out";
Destructuring
let [first, second] = [1, 2];
// swap variables
[first, second] = [second, first];
// destructure arrays
let [first, ...rest] = [1, 2, 3, 4];
let [, second, , fourth] = [1, 2, 3, 4];
// objects
let o = {
a: "foo",
b: 12,
c: "bar"
}
let {a, b} = o;
Usage
npm install -g typescript
tsc hello.ts
class Student {
fullName: string;
constructor(public firstName, public
middleInitial, public lastName) {
this.fullName = firstName + " " +
middleInitial + " " + lastName;
}
}
interface Person {
firstName: string;
lastName: string;
}
function greeter(person : Person) {
return "Hello, " + person.firstName + " " +
person.lastName;
}
var user = new Student("Jane", "M.", "User");
document.body.innerHTML = greeter(user);
var Student = (function () {
function Student(firstName, middleInitial,
lastName) {
this.firstName = firstName;
this.middleInitial = middleInitial;
this.lastName = lastName;
this.fullName = firstName + " " +
middleInitial + " " + lastName;
}
return Student;
}());
function greeter(person) {
return "Hello, " + person.firstName + " " +
person.lastName;
}
var user = new Student("Jane", "M.", "User");
document.body.innerHTML = greeter(user);
DEMO
TypeScript Integrations
• grunt
• gulp
• browserify
• webpack
• jspm
Variable scoping
var foo: string = 'bar';
let foo: string = 'bar';
const foo: string = 'bar';
var let const
scope function block block
immutable No No Yes
Standard ever ES2015 / TS ES2015 / TS
Usecase Not any more ~30% ~70%
DEMO
Variable scoping
function f(condition: boolean, x: number) {
if (condition) {
let x = 100;
return x;
}
return x;
}
f(false, 0); // returns 0
f(true, 0); // returns 100
Variable scoping
function f(condition, x) {
if (condition) {
var x_1 = 100;
return x_1;
}
return x;
}
f(false, 0); // returns 0
f(true, 0); // returns 100
Interfaces
interface Person {
firstName: string;
lastName: string;
middleName?: string;
}
function combinedName(person: Person): string {
if (person.middleName) {
return person.middleName + ' ' + person.lastName;
} else {
return person.firstName + ' ' + person.lastName;
}
}
Inheriting interfaces
interface Shape {
color: string;
}
interface Square extends Shape {
sideLength: number;
}
const square = <Square>{};
square.color = "blue";
square.sideLength = 10;
Classes
interface ClockConstructor {
new (hour: number, minute: number): ClockInterface;
}
interface ClockInterface {
tick();
}
function createClock(ctor: ClockConstructor, hour: number, minute: number):
ClockInterface {
return new ctor(hour, minute);
}
class DigitalClock implements ClockInterface {
constructor(h: number, m: number) { }
tick() {
console.log("beep beep");
}
}
class AnalogClock implements ClockInterface {
constructor(h: number, m: number) { }
tick() {
console.log("tick tock");
}
}
let digital = createClock(DigitalClock, 12, 17);
let analog = createClock(AnalogClock, 7, 32);
Classes property visibility
class Person {
protected name: string;
constructor(name: string) { this.name = name; }
}
class Employee extends Person {
private department: string;
constructor(name: string, department: string) {
super(name);
this.department = department;
}
public getElevatorPitch() {
return `Hello, my name is ${this.name} and I work in $
{this.department}.`;
}
}
let howard = new Employee("Howard", "Sales");
console.log(howard.getElevatorPitch());
console.log(howard.name); // error
Interfaces extending Classes
class Control {
private state: any;
}
interface SelectableControl extends Control {
select(): void;
}
class Button extends Control {
select() { }
}
class TextBox extends Control {
select() { }
}
class Image extends Control {
}
class Location {
select() { }
}
Solving the "this" problem
$('#any-button').on('click', function() {
$(this).text('Clicked');
$.get('http://some.api/foo.json').success(function(){
$(this).text('Result');
});
}
$('#any-button').on('click', function() {
$(this).text('Clicked');
var btn = this;
$.get('http://some.api/foo.json').success(function(){
$(btn).text('Result');
});
}
Fatarrow
$('#any-button').on('click', function() {
$(this).text('Clicked');
$.get('http://some.api/foo.json').success(() => {
$(this).text('Result');
});
}
const sum = (a, b) => a+b
const even = n => {
const rest = n % 2
return rest === 0
}
Generics
function identity<T>(arg: T): T {
return arg;
}
let strOutput = identity<string>("foobar");
let numOutput = identity<number>(42);
Generics
class Cake {…}
class Phone {…}
class Box {…}
function box <T> (content: T): Box<T> {
const myBox = new Box<T>(content);
return myBox;
}
box<Cake>(new Cake()) // a box with a cake
box<Phone>(new Phone()) // a box with a phone
box(new Cake()) // also a box with a cake => inference
Iterables
let list = [4, 5, 6];
for (let i in list) {
console.log(i); // "0", "1", "2",
}
for (let i of list) {
console.log(i); // "4", "5", "6"
}
Modules
• Scoping of variables (out of global)
• Code re-use
• Lazy/Async loadable
• Encapsulation
• DRY
• Ease of testing
Modules
• No Modules (or IIFE)
• CommonJS (node.js, SystemJS, Browserify)
• AMD (require.js, SystemJS)
• ES6 (for ES2015 compatible modules)
https://0fps.net/2013/01/22/commonjs-why-and-how/
Modules
export interface IBook {
title: string
pages: number
}
export default class Book implements IBook {
constructor(public title: string, public
pages: number){}
}
import Book, {IBook} from './book'
export interface IBookshelf {
books: IBook[]
maxSize: number
}
export default class Bookshelf implements
IBookshelf {
books: IBook[] = []
constructor (public maxSize: number) {}
addBook (book: IBook) {
if (this.books.length < this.maxSize) {
this.books.push(book)
}
}
import Book from './book'
import Bookshelf from './bookshelf'
let myBookshelf = new Bookshelf(40)
let tsHandbook = new Book('TS Handbook', 42)
myBookshelf.addBook(tsHandbook)
book.ts
bookshelf.ts
index.ts
DEMO
JavaScript integration
• Already loaded JS libs are ambient modules
• Typedefinition files [library].d.ts provide typed
interfaces for TypeScript
• Typings is a Definition Manager that loads,
updates and maintains definition files
https://github.com/Microsoft/TypeScriptSamples/tree/master/jquery
hhoechtl@1drop.de

@hhoechtl

http://blog.1drop.de

Weitere ähnliche Inhalte

Was ist angesagt?

ClojurianからみたElixir
ClojurianからみたElixirClojurianからみたElixir
ClojurianからみたElixirKent Ohashi
 
Implementing Software Machines in C and Go
Implementing Software Machines in C and GoImplementing Software Machines in C and Go
Implementing Software Machines in C and GoEleanor McHugh
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsAlfonso Peletier
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Baruch Sadogursky
 
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...tdc-globalcode
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my dayTor Ivry
 
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBTDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBtdc-globalcode
 
Go for the paranoid network programmer, 3rd edition
Go for the paranoid network programmer, 3rd editionGo for the paranoid network programmer, 3rd edition
Go for the paranoid network programmer, 3rd editionEleanor McHugh
 
Design Pattern Observations
Design Pattern ObservationsDesign Pattern Observations
Design Pattern ObservationsDmitri Nesteruk
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 

Was ist angesagt? (20)

Java VS Python
Java VS PythonJava VS Python
Java VS Python
 
Go a crash course
Go   a crash courseGo   a crash course
Go a crash course
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
ClojurianからみたElixir
ClojurianからみたElixirClojurianからみたElixir
ClojurianからみたElixir
 
Collection Core Concept
Collection Core ConceptCollection Core Concept
Collection Core Concept
 
Beginning Python
Beginning PythonBeginning Python
Beginning Python
 
Implementing Software Machines in C and Go
Implementing Software Machines in C and GoImplementing Software Machines in C and Go
Implementing Software Machines in C and Go
 
Why Learn Python?
Why Learn Python?Why Learn Python?
Why Learn Python?
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014
 
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBTDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
 
Go for the paranoid network programmer, 3rd edition
Go for the paranoid network programmer, 3rd editionGo for the paranoid network programmer, 3rd edition
Go for the paranoid network programmer, 3rd edition
 
Design Pattern Observations
Design Pattern ObservationsDesign Pattern Observations
Design Pattern Observations
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Introduction to TypeScript
Introduction to TypeScriptIntroduction to TypeScript
Introduction to TypeScript
 
Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
 
Introduction to TypeScript
Introduction to TypeScriptIntroduction to TypeScript
Introduction to TypeScript
 

Ähnlich wie TypeScript: An Introduction to the Popular JavaScript Superset

What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
The Ring programming language version 1.5 book - Part 3 of 31
The Ring programming language version 1.5 book - Part 3 of 31The Ring programming language version 1.5 book - Part 3 of 31
The Ring programming language version 1.5 book - Part 3 of 31Mahmoud Samir Fayed
 
The Ring programming language version 1.5.2 book - Part 14 of 181
The Ring programming language version 1.5.2 book - Part 14 of 181The Ring programming language version 1.5.2 book - Part 14 of 181
The Ring programming language version 1.5.2 book - Part 14 of 181Mahmoud Samir Fayed
 
KotlinForJavaDevelopers-UJUG.pptx
KotlinForJavaDevelopers-UJUG.pptxKotlinForJavaDevelopers-UJUG.pptx
KotlinForJavaDevelopers-UJUG.pptxIan Robertson
 
The Ring programming language version 1.10 book - Part 22 of 212
The Ring programming language version 1.10 book - Part 22 of 212The Ring programming language version 1.10 book - Part 22 of 212
The Ring programming language version 1.10 book - Part 22 of 212Mahmoud Samir Fayed
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewPaulo Morgado
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlinThijs Suijten
 
Best of build 2021 - C# 10 & .NET 6
Best of build 2021 -  C# 10 & .NET 6Best of build 2021 -  C# 10 & .NET 6
Best of build 2021 - C# 10 & .NET 6Moaid Hathot
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Guillaume Laforge
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Node lt
Node ltNode lt
Node ltsnodar
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practicesfelixbillon
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+ConFoo
 
Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on PythonSumit Raj
 

Ähnlich wie TypeScript: An Introduction to the Popular JavaScript Superset (20)

What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
The Ring programming language version 1.5 book - Part 3 of 31
The Ring programming language version 1.5 book - Part 3 of 31The Ring programming language version 1.5 book - Part 3 of 31
The Ring programming language version 1.5 book - Part 3 of 31
 
The Ring programming language version 1.5.2 book - Part 14 of 181
The Ring programming language version 1.5.2 book - Part 14 of 181The Ring programming language version 1.5.2 book - Part 14 of 181
The Ring programming language version 1.5.2 book - Part 14 of 181
 
KotlinForJavaDevelopers-UJUG.pptx
KotlinForJavaDevelopers-UJUG.pptxKotlinForJavaDevelopers-UJUG.pptx
KotlinForJavaDevelopers-UJUG.pptx
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
The Ring programming language version 1.10 book - Part 22 of 212
The Ring programming language version 1.10 book - Part 22 of 212The Ring programming language version 1.10 book - Part 22 of 212
The Ring programming language version 1.10 book - Part 22 of 212
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
 
Initial Java Core Concept
Initial Java Core ConceptInitial Java Core Concept
Initial Java Core Concept
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
Best of build 2021 - C# 10 & .NET 6
Best of build 2021 -  C# 10 & .NET 6Best of build 2021 -  C# 10 & .NET 6
Best of build 2021 - C# 10 & .NET 6
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
C# - What's next
C# - What's nextC# - What's next
C# - What's next
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Node lt
Node ltNode lt
Node lt
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
 
C# for Java Developers
C# for Java DevelopersC# for Java Developers
C# for Java Developers
 
Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on Python
 

Kürzlich hochgeladen

Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROmotivationalword821
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 

Kürzlich hochgeladen (20)

Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTRO
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 

TypeScript: An Introduction to the Popular JavaScript Superset

  • 1.
  • 3. Hans Höchtl Technical Director @ Onedrop PHP, Java, Ruby Developer TYPO3 Solr, Neos
  • 4. Back in time to the beginning of
  • 5. JavaScript • Developed in 10 days back in 1995 • Target: Easy script interaction for hobby programmers in the browser, who can’t write Java • 1996 handed over to ECMA for standardization • ECMAScript 5 (spec. 1999) supported by all browsers (>=IE9)
  • 6. JavaScript - What happened? • CoffeeScript • Modularization (requireJS, AMD, etc.) • jQuery • NodeJS
  • 7. JavaScript - In the enterprise? • Not typesafe • No objects/classes • Hard to test • Bad Async handling
  • 8. TypeScript to the rescue • Released 2012 by Microsoft • Developed by Anders Hejlsberg (C#, Delphi) • Compiles to JavaScript (configurable version) • Full OOP • Type-safe • JavaScript compatible
  • 10. Buzzword bingo Types var / let / const Inheritance Promises Generics Fat arrow Interfaces Decorators public / private Moduls Class
  • 11. Typing var foo: string = 'bar'; var bar: any = ['lorem', 2]; function (p: Person) { console.log(p.lastName); } function getAddress(): Address { return this.address; } function getCountAndObject(): [number, any] { return [this.addresses.length, this.addresses]; }
  • 12. Types // Primitives var foo: string = 'bar'; var bar: any = ['lorem', 2]; // Arrays var listOfSomething: number[] = [1,2,3]; var listOfSomething: Array<number> = [1,2,3]; // Tuples var tuple: [string, number] = ['Hello', 5]; // Enum enum Color {Red, Green, Blue}; var c: Color = Color.Green; // Casting let someValue: any = "this is a string"; let strLength: number = (<string>someValue).length; // Literals type Easing = "ease-in" | "ease-out" | "ease-in-out";
  • 13. Destructuring let [first, second] = [1, 2]; // swap variables [first, second] = [second, first]; // destructure arrays let [first, ...rest] = [1, 2, 3, 4]; let [, second, , fourth] = [1, 2, 3, 4]; // objects let o = { a: "foo", b: 12, c: "bar" } let {a, b} = o;
  • 14. Usage npm install -g typescript tsc hello.ts class Student { fullName: string; constructor(public firstName, public middleInitial, public lastName) { this.fullName = firstName + " " + middleInitial + " " + lastName; } } interface Person { firstName: string; lastName: string; } function greeter(person : Person) { return "Hello, " + person.firstName + " " + person.lastName; } var user = new Student("Jane", "M.", "User"); document.body.innerHTML = greeter(user); var Student = (function () { function Student(firstName, middleInitial, lastName) { this.firstName = firstName; this.middleInitial = middleInitial; this.lastName = lastName; this.fullName = firstName + " " + middleInitial + " " + lastName; } return Student; }()); function greeter(person) { return "Hello, " + person.firstName + " " + person.lastName; } var user = new Student("Jane", "M.", "User"); document.body.innerHTML = greeter(user);
  • 15. DEMO
  • 16. TypeScript Integrations • grunt • gulp • browserify • webpack • jspm
  • 17. Variable scoping var foo: string = 'bar'; let foo: string = 'bar'; const foo: string = 'bar'; var let const scope function block block immutable No No Yes Standard ever ES2015 / TS ES2015 / TS Usecase Not any more ~30% ~70%
  • 18. DEMO
  • 19. Variable scoping function f(condition: boolean, x: number) { if (condition) { let x = 100; return x; } return x; } f(false, 0); // returns 0 f(true, 0); // returns 100
  • 20. Variable scoping function f(condition, x) { if (condition) { var x_1 = 100; return x_1; } return x; } f(false, 0); // returns 0 f(true, 0); // returns 100
  • 21. Interfaces interface Person { firstName: string; lastName: string; middleName?: string; } function combinedName(person: Person): string { if (person.middleName) { return person.middleName + ' ' + person.lastName; } else { return person.firstName + ' ' + person.lastName; } }
  • 22. Inheriting interfaces interface Shape { color: string; } interface Square extends Shape { sideLength: number; } const square = <Square>{}; square.color = "blue"; square.sideLength = 10;
  • 23. Classes interface ClockConstructor { new (hour: number, minute: number): ClockInterface; } interface ClockInterface { tick(); } function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface { return new ctor(hour, minute); } class DigitalClock implements ClockInterface { constructor(h: number, m: number) { } tick() { console.log("beep beep"); } } class AnalogClock implements ClockInterface { constructor(h: number, m: number) { } tick() { console.log("tick tock"); } } let digital = createClock(DigitalClock, 12, 17); let analog = createClock(AnalogClock, 7, 32);
  • 24. Classes property visibility class Person { protected name: string; constructor(name: string) { this.name = name; } } class Employee extends Person { private department: string; constructor(name: string, department: string) { super(name); this.department = department; } public getElevatorPitch() { return `Hello, my name is ${this.name} and I work in $ {this.department}.`; } } let howard = new Employee("Howard", "Sales"); console.log(howard.getElevatorPitch()); console.log(howard.name); // error
  • 25. Interfaces extending Classes class Control { private state: any; } interface SelectableControl extends Control { select(): void; } class Button extends Control { select() { } } class TextBox extends Control { select() { } } class Image extends Control { } class Location { select() { } }
  • 26. Solving the "this" problem $('#any-button').on('click', function() { $(this).text('Clicked'); $.get('http://some.api/foo.json').success(function(){ $(this).text('Result'); }); } $('#any-button').on('click', function() { $(this).text('Clicked'); var btn = this; $.get('http://some.api/foo.json').success(function(){ $(btn).text('Result'); }); }
  • 27. Fatarrow $('#any-button').on('click', function() { $(this).text('Clicked'); $.get('http://some.api/foo.json').success(() => { $(this).text('Result'); }); } const sum = (a, b) => a+b const even = n => { const rest = n % 2 return rest === 0 }
  • 28. Generics function identity<T>(arg: T): T { return arg; } let strOutput = identity<string>("foobar"); let numOutput = identity<number>(42);
  • 29. Generics class Cake {…} class Phone {…} class Box {…} function box <T> (content: T): Box<T> { const myBox = new Box<T>(content); return myBox; } box<Cake>(new Cake()) // a box with a cake box<Phone>(new Phone()) // a box with a phone box(new Cake()) // also a box with a cake => inference
  • 30. Iterables let list = [4, 5, 6]; for (let i in list) { console.log(i); // "0", "1", "2", } for (let i of list) { console.log(i); // "4", "5", "6" }
  • 31. Modules • Scoping of variables (out of global) • Code re-use • Lazy/Async loadable • Encapsulation • DRY • Ease of testing
  • 32. Modules • No Modules (or IIFE) • CommonJS (node.js, SystemJS, Browserify) • AMD (require.js, SystemJS) • ES6 (for ES2015 compatible modules) https://0fps.net/2013/01/22/commonjs-why-and-how/
  • 33. Modules export interface IBook { title: string pages: number } export default class Book implements IBook { constructor(public title: string, public pages: number){} } import Book, {IBook} from './book' export interface IBookshelf { books: IBook[] maxSize: number } export default class Bookshelf implements IBookshelf { books: IBook[] = [] constructor (public maxSize: number) {} addBook (book: IBook) { if (this.books.length < this.maxSize) { this.books.push(book) } } import Book from './book' import Bookshelf from './bookshelf' let myBookshelf = new Bookshelf(40) let tsHandbook = new Book('TS Handbook', 42) myBookshelf.addBook(tsHandbook) book.ts bookshelf.ts index.ts
  • 34. DEMO
  • 35. JavaScript integration • Already loaded JS libs are ambient modules • Typedefinition files [library].d.ts provide typed interfaces for TypeScript • Typings is a Definition Manager that loads, updates and maintains definition files https://github.com/Microsoft/TypeScriptSamples/tree/master/jquery