Back to the Future with TypeScript

51
Back to the future with ES2015 and TypeScript Brought to you by @ Aleš Najmann Jumpshot

Transcript of Back to the Future with TypeScript

Back to the futurewith ES2015 and TypeScriptBrought to you by @ Aleš Najmann Jumpshot

Agenda1. The rise of JavaScript2. JavaScript development

challenges3. EcmaScript on the edge of 20154. The rise of TypeScript5. Where is our profit? Q & A

!! Warning !!There will be code

The rise of JavaScriptFirst browser war (>1995)EcmaScript Standardization: 97, 98, 99, , 09, 15Server-side JavaScript (2009)

Server-side JavaScriptNode.js based on V8 (Chrome) JavaScript engine.

Modules exist but they are loaded synchronously and that makes themimpossible to use in browser.

...or need specialised bundler like browserify

Just a note...JavaScript is a trademark of Oracle Corporation.

Traditional Development challengesAbsence of stronger structuring capabilities

No modulesNo classes...but Prototype chain to a rescueNo static typesSingle-threaded execution model...still asyncDOM - terribilis estBrowser differencesand there is more...

EcmaScript 2015 features(productivity boost)

Arrow functionsTemplate stringsClasses, SubclassesDestructuringDefault + Rest + SpreadLet + ConstIterators + For..OfGeneratorsModulesPromisesand 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 featuresPromisesMath + Number + String + Array + Object APIsUnicode, Symbols, ProxiesTail calls, Reflect API...

The rise of TypeScriptMicrosoft initiative developed entirely on Github under APL 2.0Lead developer is Anders Hejlsberg, author of Turbo Pascal, Delphiand C#Originated from the perceived shortcomings of JavaScript for thedevelopment of large-scale applications

TypeScriptWhat's the deal? let's look at the conversation on irc serverfreenode.net channel #typescript

TypeScript is a typed superset of JavaScript that compiles to plainJavaScript.

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, interfacesfill the role of naming these types, and are apowerful way of defining contracts within yourcode as well as contracts with code outside ofyour 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

ModulesTypeScript supports namespaces and modules throught ES2015 syntaxand compiles them down to:

CommonJSAMDSystemJSUMDES6

TypesAny typePrimitive typesObject typesUnion typesIntersection typesType parametersSpecifying types (literals etc.)

Any typeis a supertype of all types, and is assignable to and from all types.

In general, in places where a type is not explicitly provided andTypeScript 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 typesNumberBooleanStringSymbolVoidNullUndefinedEnum

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 absenceof a value and is used as the return type of functions with no returnvalue.

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 primitivetype and is the type of the null literal.

The null literal references the one and only value of the Null type. It isnot possible to directly reference the Null type itself.

The Null type is a subtype of all types, except the Undefined type. Thismeans that null is considered a valid value for all primitive types, objecttypes, union types, intersection types, and type parameters, includingeven 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 uninitializedvariables and is the one and only value of the Undefined type. It is notpossible 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 typeTuple typeFunction typeConstrutor typeType parametersOverloading

Array types

The declaration of the 'Array' interface includes a property 'length' anda numeric index signature for the element type, along with othermembers

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 HTMLSpanElementlet div = document.createElement("div"); // return type is HTMLDivElementlet 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

Toolingtsc - TypeScript Compiler (Yaay!)tsd - TypeScript definiton managertypings - Yet another TypeScript definition managertslint - linter and code quality tooltsserver - typescript compiler as servicejspm - package manager for systemjs modulesWebStorm has builtin pluginAtom has plugin(s)Sublime Text has pluginVisual Studio Code (VSCode)NPM packages like tsify, grunt-ts etc.More on Github Wiki

Q & A...like

ReferencesES6 features: TypeScript Homepage: DefinitelyTyped: TypeScript Deep Dive:

github.com/lukehoban/es6featurestypescriptlang.org

definitelytyped.org/tsdbasarat.gitbooks.io/typescript