SlideShare a Scribd company logo
1 of 51
Download to read offline
Back to the future
with ES2015 and TypeScript
Brought to you by @Aleš Najmann Jumpshot
Agenda
1. The rise of JavaScript
2. JavaScript development
challenges
3. EcmaScript on the edge of 2015
4. The rise of TypeScript
5. Where is our profit? Q & A
!! Warning !!
There will be code
The rise of JavaScript
First browser war (>1995)
EcmaScript Standardization: 97, 98, 99, , 09, 15
Server-side JavaScript (2009)
Server-side JavaScript
Node.js based on V8 (Chrome) JavaScript engine.
Modules exist but they are loaded synchronously and that makes them
impossible to use in browser.
...or need specialised bundler like browserify
Just a note...
JavaScript is a trademark of Oracle Corporation.
Traditional Development challenges
Absence of stronger structuring capabilities
No modules
No classes
...but Prototype chain to a rescue
No static types
Single-threaded execution model
...still async
DOM - terribilis est
Browser differences
and there is more...
EcmaScript 2015 features
(productivity boost)
Arrow functions
Template strings
Classes, Subclasses
Destructuring
Default + Rest + Spread
Let + Const
Iterators + For..Of
Generators
Modules
Promises
and there is more...
Fat Arrow functions
// Expression bodies
var odds = evens.map(v => v + 1);
var nums = evens.map((v, i) => v + i);
var pairs = evens.map(v => ({even: v, odd: v + 1}));
// Statement bodies
nums.forEach(v => {
if (v % 5 === 0)
fives.push(v);
}
);
Fat Arrow functions
// Lexical this
var bob = {
_name: "Bob",
_friends: ["Jane", "Frank"],
printFriends() {
this._friends.forEach(f =>
console.log(this._name + " knows " + f));
}
}
Template strings
// Basic literal string creation
`In JavaScript 'n' is a line-feed.`
// Multiline strings
`Before ES2015 this is
not legal.`
function twice(x: number): number {
return x * 2;
}
// String interpolation (or templates)
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`
`Twice 3 is ${twice(3)}`
Classes
class Animal {
constructor(name) { this._name = name; }
myApiMethod() { return 'Oh hai!'; }
get name() { return this._name; }
static createLemming() { return new Animal('Lemming'); }
}
SubClasses
class MyElement extends HTMLElement {
constructor() { super(); } // super call is required
myApiMethod() { return 'Oh hai!'; }
toString() { return "MyElement"; }
}
Let + Const
Let is block scoped rather than function scoped like var.
// let is new var ;)
let sayHi = 'Oh hai!';
// const makes things final
const king = {
name: 'John Snow',
title: 'The King in the North'
};
Destructuring
// completely statically checked
let [hello, world] = ['hello', 'world'];
const {name, title} = {
name: 'John Snow',
title: 'The King in the North'
};
let [a, b, c] = [10, 20]; // an error
let [a, b] = [10, 20, 30]; // ok
Default + Rest + Spread
function adder(x, y=12) { // Default value: y is 12 if not passed
return x + y;
}
adder(3) == 15;
function multiplyLen(x, ...y) { // Rest operator: y is an Array
return x * y.length;
}
multiplyLen(3, "hello", true) == 6
function adder2(x, y, z) {
return x + y + z;
}
// Spread operator: Pass each elem of array as argument
adder2(...[1,2,3]) == 6
For...of
let arr = ['a', 'b', 'c'];
for (let elem of arr) {
console.log(elem);
}
Other features
Promises
Math + Number + String + Array + Object APIs
Unicode, Symbols, Proxies
Tail calls, Reflect API
...
The rise of TypeScript
Microsoft initiative developed entirely on Github under APL 2.0
Lead developer is Anders Hejlsberg, author of Turbo Pascal, Delphi
and C#
Originated from the perceived shortcomings of JavaScript for the
development of large-scale applications
TypeScript
What's the deal? let's look at the conversation on irc server
freenode.net channel #typescript
TypeScript is a typed superset of JavaScript that compiles to plain
JavaScript.
07:11 <Ian_Corne> can I use all ES6 syntax in typescript :)
07:16 <halcyon> Ian_Corne: yes, you can
07:16 <Ian_Corne> Ok, thanks, great!
Type System & Interfaces
One of TypeScript's core principles is that type­
checking focuses on the shape that values have.
This is sometimes called "duck typing" or
"structural subtyping". In TypeScript, interfaces
fill the role of naming these types, and are a
powerful way of defining contracts within your
code as well as contracts with code outside of
your project.
Ambient declarations
It is also a general way how to add types to foreign javascript code.
Thanks to definition files: *.d.ts
// what if jQuery is present, but compiler doesn't know that
declare module "jquery" {
export = $;
}
declare var jQuery: JQueryStatic; // inteface
declare var $: JQueryStatic; // inteface
Modules
TypeScript supports namespaces and modules throught ES2015 syntax
and compiles them down to:
CommonJS
AMD
SystemJS
UMD
ES6
Types
Any type
Primitive types
Object types
Union types
Intersection types
Type parameters
Specifying types (literals etc.)
Any type
is a supertype of all types, and is assignable to and from all types.
In general, in places where a type is not explicitly provided and
TypeScript cannot infer one, the Any type is assumed.
var notSure: any = 4;
notSure.ifItExists(); // okay, if ItExists might exist at runtime
notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check)
var prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.
Primitive types
Number
Boolean
String
Symbol
Void
Null
Undefined
Enum
Numbers
let f1: number;
let f2: number = 1;
let f3: number = 3.1415926; // float-point number
let f4 = 2.71828183; // inferred float-point number
let f5: number = 3.1415926; // float-point number
let f6 = 2.71828183; // inferred float-point number
const f7 = 0x6ff; // hexadecimal number
const f8 = 0o700; // octal number
const f9 = 0b10101; // binary number
function subtract(i: number = 0, j: number = 0) {
return i - j;
}
Booleans
let almostDone: boolean; // uninitialized
let isDone: boolean = true; // explicitly initialized
let wasDone = false; // inferred (always initialized)
var done: boolean = false; // old style var
function neg(n: boolean = false): boolean {
return !n;
}
Strings
let title: string; // uninitialized
const name: string = 'Edward'; // explicitly initialized
const surname = 'Diego'; // inferred
Void
The Void type, referenced by the void keyword, represents the absence
of a value and is used as the return type of functions with no return
value.
The only possible values for the Void type are null and undefined
function x(): void {
return null;
}
Null
The Null type corresponds to the similarly named JavaScript primitive
type and is the type of the null literal.
The null literal references the one and only value of the Null type. It is
not possible to directly reference the Null type itself.
The Null type is a subtype of all types, except the Undefined type. This
means that null is considered a valid value for all primitive types, object
types, union types, intersection types, and type parameters, including
even the Number and Boolean primitive types.
var n: number = null; // Primitives can be null
var x = null; // Same as x: any = null
var e: Null; // Error, can't reference Null type
Undefined
The undefined literal denotes the value given to all uninitialized
variables and is the one and only value of the Undefined type. It is not
possible to directly reference the Undefined type itself.
var n: number; // Same as n: number = undefined
var x = undefined; // Same as x: any = undefined
var e: Undefined; // Error, can't reference Undefined type
Enums
enum Color {Red, Green, Blue};
var c: Color = Color.Green;
enum Color {Red = 1, Green, Blue};
var c: Color = Color.Green;
var colorName: string = Color[2]; // 'Green'
Object types
Array type
Tuple type
Function type
Construtor type
Type parameters
Overloading
Array types
The declaration of the 'Array' interface includes a property 'length' and
a numeric index signature for the element type, along with other
members
interface Array<T> {
length: number;
[x: number]: T;
// Other members
}
// example of literal
var a: string[] = ["hello", "world"];
let list1: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3]; // generics style
let list3 = ['hello', 'hi']; // inferred string[]
list3.push(1); // this one won't compile!
let list4: any = ['hello', 'or', 'hi'];
list4.push(1); // this one gonna be ok
Tuple types
represent JavaScript arrays with individually tracked element types.
var t: [number, string] = [3, "three"];
var n = t[0]; // Type of n is number
var s = t[1]; // Type of s is string
Function types
interface SomeFn {
(x: number): number;
}
let myFn = (x: number) => x * 2;
let myFn2: SomeFn = myFn;
Constructor types
interface SomeCons {
new(x: number);
}
class Example {
private x: number;
constructor(x: number) {
this.x = x;
}
}
let ConcreteCons: SomeCons = Example;
let y = new ConcreteCons(10);
Type parameters
<T>(x: T): T // simple
<T>(x: T, y: T): T[]
// A function taking two arguments of different types,
// returning an object with properties 'x' and 'y' of those types:
<T, U>(x: T, y: U): { x: T; y: U; }
// A function taking an array of one type and a function argument,
// returning an array of another type, where the function
// argument takes a value of the first array element type
// and returns a value of the second array element type:
<T, U>(a: T[], f: (x: T) => U): U[]
Overloading on string parameters
interface Document {
createElement(tagName: "div"): HTMLDivElement;
createElement(tagName: "span"): HTMLSpanElement;
createElement(tagName: "canvas"): HTMLCanvasElement;
createElement(tagName: string): HTMLElement;
}
let span = document.createElement("span"); // return type is HTMLSpanElement
let div = document.createElement("div"); // return type is HTMLDivElement
let someElm = document.createElement("element"); // return type is ? :)
Union types
let x: string | number;
x = "hello"; // Ok
x = 42; // Ok
x = test; // Error, boolean not assignable
x = test ? 5 : "five"; // Ok
x = test ? 0 : false; // Error, number | boolean not assignable
Intersection types
interface A { a: number }; interface B { b: number }
let ab: A & B = { a: 1, b: 1 };
let a: A = ab; // A & B assignable to A
let b: B = ab; // A & B assignable to B
interface X { p: A }; interface Y { p: B }
let xy: X & Y = { p: ab }; // X & Y has property p of type A & B
type F1 = (a: string, b: string) => void;
type F2 = (a: number, b: number) => void;
let f: F1 & F2 = (a: string | number, b: string | number) => { };
f("hello", "world"); // Ok
f(1, 2); // Ok
f(1, "test"); // Error
Tooling
tsc - TypeScript Compiler (Yaay!)
tsd - TypeScript definiton manager
typings - Yet another TypeScript definition manager
tslint - linter and code quality tool
tsserver - typescript compiler as service
jspm - package manager for systemjs modules
WebStorm has builtin plugin
Atom has plugin(s)
Sublime Text has plugin
Visual Studio Code (VSCode)
NPM packages like tsify, grunt-ts etc.
More on Github Wiki
Q & A
...like
References
ES6 features:
TypeScript Homepage:
DefinitelyTyped:
TypeScript Deep Dive:
github.com/lukehoban/es6features
typescriptlang.org
definitelytyped.org/tsd
basarat.gitbooks.io/typescript

More Related Content

What's hot

Cocoa for Web Developers
Cocoa for Web DevelopersCocoa for Web Developers
Cocoa for Web Developersgeorgebrock
 
C++11 concurrency
C++11 concurrencyC++11 concurrency
C++11 concurrencyxu liwei
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityGeorgePeterBanyard
 
Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Geeks Anonymes
 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpMichael Stal
 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmersMark Whitaker
 
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++Mihai Todor
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScriptT11 Sessions
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...Francesco Casalegno
 
All You Need to Know About Type Script
All You Need to Know About Type ScriptAll You Need to Know About Type Script
All You Need to Know About Type ScriptFolio3 Software
 
Introduction to-csharp
Introduction to-csharpIntroduction to-csharp
Introduction to-csharpSDFG5
 

What's hot (20)

C++ Training
C++ TrainingC++ Training
C++ Training
 
C++ Presentation
C++ PresentationC++ Presentation
C++ Presentation
 
Cocoa for Web Developers
Cocoa for Web DevelopersCocoa for Web Developers
Cocoa for Web Developers
 
C++11 concurrency
C++11 concurrencyC++11 concurrency
C++11 concurrency
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing Insanity
 
Le langage rust
Le langage rustLe langage rust
Le langage rust
 
Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)
 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharp
 
Introduction to Swift
Introduction to SwiftIntroduction to Swift
Introduction to Swift
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmers
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 
C++11
C++11C++11
C++11
 
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
 
All You Need to Know About Type Script
All You Need to Know About Type ScriptAll You Need to Know About Type Script
All You Need to Know About Type Script
 
Introduction to-csharp
Introduction to-csharpIntroduction to-csharp
Introduction to-csharp
 

Similar to Back to the Future with TypeScript

Type script - advanced usage and practices
Type script  - advanced usage and practicesType script  - advanced usage and practices
Type script - advanced usage and practicesIwan van der Kleijn
 
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 1Troy Miles
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScriptGarth Gilmour
 
Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...Arthur Puthin
 
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
 
C++ Tutorial.docx
C++ Tutorial.docxC++ Tutorial.docx
C++ Tutorial.docxPinkiVats1
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupSyedHaroonShah4
 
Practical TypeScript
Practical TypeScriptPractical TypeScript
Practical TypeScriptldaws
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2Warui Maina
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)allanh0526
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Chris Adamson
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyGrejoJoby1
 

Similar to Back to the Future with TypeScript (20)

Type script - advanced usage and practices
Type script  - advanced usage and practicesType script  - advanced usage and practices
Type script - advanced usage and practices
 
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
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
C# overview part 1
C# overview part 1C# overview part 1
C# overview part 1
 
recap-js-and-ts.pdf
recap-js-and-ts.pdfrecap-js-and-ts.pdf
recap-js-and-ts.pdf
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 
Csharp4 basics
Csharp4 basicsCsharp4 basics
Csharp4 basics
 
Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...
 
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
 
C++ Tutorial.docx
C++ Tutorial.docxC++ Tutorial.docx
C++ Tutorial.docx
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
 
Day 1
Day 1Day 1
Day 1
 
Practical TypeScript
Practical TypeScriptPractical TypeScript
Practical TypeScript
 
Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
 
C# - Part 1
C# - Part 1C# - Part 1
C# - Part 1
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
 
Java script
Java scriptJava script
Java script
 

Recently uploaded

WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2
 
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
WSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration ToolingWSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration ToolingWSO2
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationJuha-Pekka Tolvanen
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...
WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...
WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...WSO2
 

Recently uploaded (20)

WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
WSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration ToolingWSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration Tooling
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...
WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...
WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...
 

Back to the Future with TypeScript

  • 1. Back to the future with ES2015 and TypeScript Brought to you by @Aleš Najmann Jumpshot
  • 2.
  • 3. Agenda 1. The rise of JavaScript 2. JavaScript development challenges 3. EcmaScript on the edge of 2015 4. The rise of TypeScript 5. Where is our profit? Q & A
  • 4. !! Warning !! There will be code
  • 5. The rise of JavaScript First browser war (>1995) EcmaScript Standardization: 97, 98, 99, , 09, 15 Server-side JavaScript (2009)
  • 6. Server-side JavaScript Node.js based on V8 (Chrome) JavaScript engine. Modules exist but they are loaded synchronously and that makes them impossible to use in browser. ...or need specialised bundler like browserify
  • 7. Just a note... JavaScript is a trademark of Oracle Corporation.
  • 8. Traditional Development challenges Absence of stronger structuring capabilities No modules No classes ...but Prototype chain to a rescue No static types Single-threaded execution model ...still async DOM - terribilis est Browser differences and there is more...
  • 9.
  • 10. EcmaScript 2015 features (productivity boost) Arrow functions Template strings Classes, Subclasses Destructuring Default + Rest + Spread Let + Const Iterators + For..Of Generators Modules Promises and there is more...
  • 11. Fat Arrow functions // Expression bodies var odds = evens.map(v => v + 1); var nums = evens.map((v, i) => v + i); var pairs = evens.map(v => ({even: v, odd: v + 1})); // Statement bodies nums.forEach(v => { if (v % 5 === 0) fives.push(v); } );
  • 12. Fat Arrow functions // Lexical this var bob = { _name: "Bob", _friends: ["Jane", "Frank"], printFriends() { this._friends.forEach(f => console.log(this._name + " knows " + f)); } }
  • 13. Template strings // Basic literal string creation `In JavaScript 'n' is a line-feed.` // Multiline strings `Before ES2015 this is not legal.` function twice(x: number): number { return x * 2; } // String interpolation (or templates) var name = "Bob", time = "today"; `Hello ${name}, how are you ${time}?` `Twice 3 is ${twice(3)}`
  • 14. Classes class Animal { constructor(name) { this._name = name; } myApiMethod() { return 'Oh hai!'; } get name() { return this._name; } static createLemming() { return new Animal('Lemming'); } }
  • 15. SubClasses class MyElement extends HTMLElement { constructor() { super(); } // super call is required myApiMethod() { return 'Oh hai!'; } toString() { return "MyElement"; } }
  • 16. Let + Const Let is block scoped rather than function scoped like var. // let is new var ;) let sayHi = 'Oh hai!'; // const makes things final const king = { name: 'John Snow', title: 'The King in the North' };
  • 17. Destructuring // completely statically checked let [hello, world] = ['hello', 'world']; const {name, title} = { name: 'John Snow', title: 'The King in the North' }; let [a, b, c] = [10, 20]; // an error let [a, b] = [10, 20, 30]; // ok
  • 18. Default + Rest + Spread function adder(x, y=12) { // Default value: y is 12 if not passed return x + y; } adder(3) == 15; function multiplyLen(x, ...y) { // Rest operator: y is an Array return x * y.length; } multiplyLen(3, "hello", true) == 6 function adder2(x, y, z) { return x + y + z; } // Spread operator: Pass each elem of array as argument adder2(...[1,2,3]) == 6
  • 19. For...of let arr = ['a', 'b', 'c']; for (let elem of arr) { console.log(elem); }
  • 20. Other features Promises Math + Number + String + Array + Object APIs Unicode, Symbols, Proxies Tail calls, Reflect API ...
  • 21.
  • 22. The rise of TypeScript Microsoft initiative developed entirely on Github under APL 2.0 Lead developer is Anders Hejlsberg, author of Turbo Pascal, Delphi and C# Originated from the perceived shortcomings of JavaScript for the development of large-scale applications
  • 23. TypeScript What's the deal? let's look at the conversation on irc server freenode.net channel #typescript TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. 07:11 <Ian_Corne> can I use all ES6 syntax in typescript :) 07:16 <halcyon> Ian_Corne: yes, you can 07:16 <Ian_Corne> Ok, thanks, great!
  • 24. Type System & Interfaces One of TypeScript's core principles is that type­ checking focuses on the shape that values have. This is sometimes called "duck typing" or "structural subtyping". In TypeScript, interfaces fill the role of naming these types, and are a powerful way of defining contracts within your code as well as contracts with code outside of your project.
  • 25. Ambient declarations It is also a general way how to add types to foreign javascript code. Thanks to definition files: *.d.ts // what if jQuery is present, but compiler doesn't know that declare module "jquery" { export = $; } declare var jQuery: JQueryStatic; // inteface declare var $: JQueryStatic; // inteface
  • 26. Modules TypeScript supports namespaces and modules throught ES2015 syntax and compiles them down to: CommonJS AMD SystemJS UMD ES6
  • 27. Types Any type Primitive types Object types Union types Intersection types Type parameters Specifying types (literals etc.)
  • 28. Any type is a supertype of all types, and is assignable to and from all types. In general, in places where a type is not explicitly provided and TypeScript cannot infer one, the Any type is assumed. var notSure: any = 4; notSure.ifItExists(); // okay, if ItExists might exist at runtime notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check) var prettySure: Object = 4; prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.
  • 30. Numbers let f1: number; let f2: number = 1; let f3: number = 3.1415926; // float-point number let f4 = 2.71828183; // inferred float-point number let f5: number = 3.1415926; // float-point number let f6 = 2.71828183; // inferred float-point number const f7 = 0x6ff; // hexadecimal number const f8 = 0o700; // octal number const f9 = 0b10101; // binary number function subtract(i: number = 0, j: number = 0) { return i - j; }
  • 31. Booleans let almostDone: boolean; // uninitialized let isDone: boolean = true; // explicitly initialized let wasDone = false; // inferred (always initialized) var done: boolean = false; // old style var function neg(n: boolean = false): boolean { return !n; }
  • 32. Strings let title: string; // uninitialized const name: string = 'Edward'; // explicitly initialized const surname = 'Diego'; // inferred
  • 33. Void The Void type, referenced by the void keyword, represents the absence of a value and is used as the return type of functions with no return value. The only possible values for the Void type are null and undefined function x(): void { return null; }
  • 34. Null The Null type corresponds to the similarly named JavaScript primitive type and is the type of the null literal. The null literal references the one and only value of the Null type. It is not possible to directly reference the Null type itself. The Null type is a subtype of all types, except the Undefined type. This means that null is considered a valid value for all primitive types, object types, union types, intersection types, and type parameters, including even the Number and Boolean primitive types. var n: number = null; // Primitives can be null var x = null; // Same as x: any = null var e: Null; // Error, can't reference Null type
  • 35. Undefined The undefined literal denotes the value given to all uninitialized variables and is the one and only value of the Undefined type. It is not possible to directly reference the Undefined type itself. var n: number; // Same as n: number = undefined var x = undefined; // Same as x: any = undefined var e: Undefined; // Error, can't reference Undefined type
  • 36. Enums enum Color {Red, Green, Blue}; var c: Color = Color.Green; enum Color {Red = 1, Green, Blue}; var c: Color = Color.Green; var colorName: string = Color[2]; // 'Green'
  • 37. Object types Array type Tuple type Function type Construtor type Type parameters Overloading
  • 38. Array types The declaration of the 'Array' interface includes a property 'length' and a numeric index signature for the element type, along with other members interface Array<T> { length: number; [x: number]: T; // Other members } // example of literal var a: string[] = ["hello", "world"]; let list1: number[] = [1, 2, 3]; let list2: Array<number> = [1, 2, 3]; // generics style let list3 = ['hello', 'hi']; // inferred string[] list3.push(1); // this one won't compile! let list4: any = ['hello', 'or', 'hi']; list4.push(1); // this one gonna be ok
  • 39.
  • 40. Tuple types represent JavaScript arrays with individually tracked element types. var t: [number, string] = [3, "three"]; var n = t[0]; // Type of n is number var s = t[1]; // Type of s is string
  • 41. Function types interface SomeFn { (x: number): number; } let myFn = (x: number) => x * 2; let myFn2: SomeFn = myFn;
  • 42. Constructor types interface SomeCons { new(x: number); } class Example { private x: number; constructor(x: number) { this.x = x; } } let ConcreteCons: SomeCons = Example; let y = new ConcreteCons(10);
  • 43. Type parameters <T>(x: T): T // simple <T>(x: T, y: T): T[] // A function taking two arguments of different types, // returning an object with properties 'x' and 'y' of those types: <T, U>(x: T, y: U): { x: T; y: U; } // A function taking an array of one type and a function argument, // returning an array of another type, where the function // argument takes a value of the first array element type // and returns a value of the second array element type: <T, U>(a: T[], f: (x: T) => U): U[]
  • 44. Overloading on string parameters interface Document { createElement(tagName: "div"): HTMLDivElement; createElement(tagName: "span"): HTMLSpanElement; createElement(tagName: "canvas"): HTMLCanvasElement; createElement(tagName: string): HTMLElement; } let span = document.createElement("span"); // return type is HTMLSpanElement let div = document.createElement("div"); // return type is HTMLDivElement let someElm = document.createElement("element"); // return type is ? :)
  • 45. Union types let x: string | number; x = "hello"; // Ok x = 42; // Ok x = test; // Error, boolean not assignable x = test ? 5 : "five"; // Ok x = test ? 0 : false; // Error, number | boolean not assignable
  • 46. Intersection types interface A { a: number }; interface B { b: number } let ab: A & B = { a: 1, b: 1 }; let a: A = ab; // A & B assignable to A let b: B = ab; // A & B assignable to B interface X { p: A }; interface Y { p: B } let xy: X & Y = { p: ab }; // X & Y has property p of type A & B type F1 = (a: string, b: string) => void; type F2 = (a: number, b: number) => void; let f: F1 & F2 = (a: string | number, b: string | number) => { }; f("hello", "world"); // Ok f(1, 2); // Ok f(1, "test"); // Error
  • 47.
  • 48. Tooling tsc - TypeScript Compiler (Yaay!) tsd - TypeScript definiton manager typings - Yet another TypeScript definition manager tslint - linter and code quality tool tsserver - typescript compiler as service jspm - package manager for systemjs modules WebStorm has builtin plugin Atom has plugin(s) Sublime Text has plugin Visual Studio Code (VSCode) NPM packages like tsify, grunt-ts etc. More on Github Wiki
  • 50.
  • 51. References ES6 features: TypeScript Homepage: DefinitelyTyped: TypeScript Deep Dive: github.com/lukehoban/es6features typescriptlang.org definitelytyped.org/tsd basarat.gitbooks.io/typescript