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

Back to the Future with TypeScript

  • 1.
    Back to thefuture with ES2015 and TypeScript Brought to you by @Aleš Najmann Jumpshot
  • 3.
    Agenda 1. The riseof 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 !! Therewill be code
  • 5.
    The rise ofJavaScript First browser war (>1995) EcmaScript Standardization: 97, 98, 99, , 09, 15 Server-side JavaScript (2009)
  • 6.
    Server-side JavaScript Node.js basedon 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... JavaScriptis a trademark of Oracle Corporation.
  • 8.
    Traditional Development challenges Absenceof 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...
  • 10.
    EcmaScript 2015 features (productivityboost) 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 // Basicliteral 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 extendsHTMLElement { constructor() { super(); } // super call is required myApiMethod() { return 'Oh hai!'; } toString() { return "MyElement"; } }
  • 16.
    Let + Const Letis 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 staticallychecked 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 ...
  • 22.
    The rise ofTypeScript 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 isalso 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 namespacesand modules throught ES2015 syntax and compiles them down to: CommonJS AMD SystemJS UMD ES6
  • 27.
    Types Any type Primitive types Objecttypes Union types Intersection types Type parameters Specifying types (literals etc.)
  • 28.
    Any type is asupertype 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'.
  • 29.
  • 30.
    Numbers let f1: number; letf2: 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 typecorresponds 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 literaldenotes 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 Tupletype Function type Construtor type Type parameters Overloading
  • 38.
    Array types The declarationof 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
  • 40.
    Tuple types represent JavaScriptarrays 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 stringparameters 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
  • 48.
    Tooling tsc - TypeScriptCompiler (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
  • 49.
  • 51.
    References ES6 features: TypeScript Homepage: DefinitelyTyped: TypeScriptDeep Dive: github.com/lukehoban/es6features typescriptlang.org definitelytyped.org/tsd basarat.gitbooks.io/typescript