TypeScript intro 19.03.2015 @Tallinn
Warning & credentials Slidesare mostly based on: –Sander Mak typescript-coding-javascript- without-the-pain –Anders Hejlsberg's video on homepage: www.typescriptlang.org Slides are packed with text –Meant for recalling the presentation people not attending the presentation –You might not want to read the slides ifYou
Agenda WhyTypeScript Language intro Demos https://github.com/atsu85/TypeScriptPlayField – TypeScript language features – TypeScript in Angular project (tiny sample) Comparison withTS alternatives Conclusion
What’s good about JS? It’s everywhere – Browsers, servers Huge amount of libraries Flexible procedural and functional
What’s wrong with JS? Dynamic typing – Can’t do type checking (but lints could help a bit) – Content-assist can’t be automatically provided for IDE’s Lack of modularity (out of the box) Verbose patterns IIFE - Immediately-invoked_function_expression Declaring/extending classes/objects
Wishlist Scalable HTML5 client side development – Modularity – Safe Refactoring Type checking Searching for method/filed usages Easily learnable for Java developers Non-invasive – Interop with existing libs – browser support Easy to debug – Clean JS output (also for exit strategy) – Map files (mapping from generated code to originaal source) Long-term vision (Language spec, future standards)
EcmaScript 6 (ES6) Current state – RC2 (March 4, 2015) Release? – "A sixth edition of the standard is currently under development with a target date of June 2015 for completion" ES6 language features with code samples: – https://github.com/lukehoban/es6features
TypeScript project Superset of JS(ES5) that compiles to JS – Compiles to ES3/ES5/ES6 – No special runtime dependencies – TypeScript 2.0 goal to be superset of ES6 Website: http://www.typescriptlang.org/ – https://github.com/Microsoft/TypeScript/wiki/Roadmap Microsoft – Anders Hejlsberg (Turbopascal, Delphy, C#,TypeScript) – Working with Flow and Angular(AtScript) teams to become best choice for writing JS OS compiler(also written inTS) and type declarations(JS core, DOM, …) – https://github.com/Microsoft/TypeScript – Apache 2.0 license Uses NodeJS for compiling – Cross platform, no MS dependencies
TS features from ES6… Classes, inheritance Interfaces Arrow functions aka Lambdas Default parameters, rest parameters (varargs) Template strings
…TS features from ES6 TS v1.4 (with compile target=ES6, plans to also allow compiling following ES6 features to ES3/ES5) – let, const Roadmap: TS v1.5 – destructuring – for..of, iterators? – unicode – External module compatibility – symbols TS v1.6 – Generators – async/await TS 2.0 "plans" – Superset of ES6
Getting started Install node InstallTypeScript: ´npm install -g typescript´ Rename extension: ´mv mycode.js mycode.ts´ Compile: ´tsc mycode.ts´
…Getting started - Got compilation error? Resolve errors related to global variables (i.e. globalVar) – declare var globalVar; WhenYou don’t have type information (and don’t want to write it Yourself) – IfYou want type info about the global variable: – See https://github.com/borisyankov/DefinitelyTyped/ – Type definitions for almost 1000 libraries declare var globalVar: someModule.SomeType; Need to reference library or type declarations of the library – /// <reference path=„path/to/my-lib.ts" /> – /// <reference path=„path/to/external-lib-type-info.d.ts" />
TypeScript language features Syntax sugar for creating – Classes, interfaces, modules, … Types: – Optional (in code, not in comments) JS isTS – add types when needed – Static Errors at compile time not at runtime – Interfaces, classes or structural Can useType names, but they are not required Checked at compile time, not runtime (unlike with „duck typing“) – Disappear after compiling
TypeScript vs Java: Classes Similar: – Can implement interfaces – Inheritance – Instance methods/members – Static methods/members – Generics (with type erasure) Different: – No method/constructor overloading – Default & optional parameters – ES6 class syntax (similar to Scala) – Mixins/traits (trivial, but no out-of-the-box syntax as in Scala)
TypeScript vs Java:Types Object -> any void -> void boolean -> boolean Integer, long, short, … -> number String, char -> string Arrays: – TypeArray[] ->TypeArray[] – primitiveTypeArray[] -> primitiveTypeArray[]
How it looks like? var varName:VarType = … ; function functionName(param1: Param1Type): RetrunType { return new RetrunType(param1); } interface IPerson { name: string; getAge(): number;} class Person implements IPerson { constructor(public name: string, private yearOfBirth: number){}; getAge() { // return type can be inferred return new Date().getFullYear() - this.yearOfBirth; // silly demo } }
Demo: Basics Type annotations Classes, interfaces, functions – Optional/default members – Optional/default function arguments Errors when using missing field/function Type inference – From assignment – From function return value to function return type – From function declared parameter type to argument passed to the function
Demo: Modules, Interfaces Open-ended –Can contribute classes/interfaces to a module from another file Can divide code into several files –Can contribute members to interface from another file Very common for jQuery plugins Modules can be imported using var: –var demo = ee.iglu.demo; –var obj = new demo.SomePublicClass();
Demo: Classes Instance fields Constructor Private fields – short notation for private fields (or fields with accessors) Static fields Default & optional parameters Inheritence
Overriding/overloading JS functions can’t be overloaded! –one function must handle all diferent type combinations, help from: Default and optional parameters Multiple signature definitions
Tricks with method signatures Basically value-agnostic signatures: interface Document { createElement(tagName: „a"): HTMLAnchorElement; createElement(tagName: "div"): HTMLDivElement; } createElement("a").href = „/main“; // OK createElement("div").href = „/main“; // ERROR div doesn't have href
More useful stuff Arrow functions a.k.a. Lambdas Enums Generics – http://www.typescriptlang.org/Playground Mixins/traits – http://www.typescriptlang.org/Handbook#mixins Union types, String interpolation – http://www.typescriptlang.org/Playground: „New Features“ Avoid infering type to „any“ type: – tsc --noImplicitAny superSolid.ts
TypeScript and external libs Search forTypeScript declarations for the lib from https://github.com/borisyankov/DefinitelyTyped/ contains type declarations for > 950 libs (~80 jQuery plugins, 30 angular plugins, toastr, moment, fullCalendar, pickadate) http://www.typescriptlang.org/Handbook#writing-dts-files Import type info from type declarations file: /// <reference path=„path/to/external-lib-type-info.d.ts" /> Import type info fromTypeScript source file: /// <reference path=„path/to/my-lib.ts" /> DEMO – UsingTypeScript with AngularJS
Summary:TypeScriptType System Type inference and structural typing – Very few type „annotations“ are necessary Formalization of JS types – Static representation of JS dynamic type system Works with existing JS libs – Out of the boxYou can treat any external JS lib object as „any“ type – Declaration files can be writter and maintained separately Not „provably type safe“ – Types reflect intent, but don't provide guarantees Type declaration files can contain mistakes
Tools:TypeScript Gradle: – Compile: https://github.com/sothmann/typescript-gradle-plugin – Monitor changes: https://github.com/bluepapa32/gradle-watch-plugin Gulp (JS build tool) – Compile: „gulp-type“ (incremental) and gulp-tsc – Watch: gulp.watch() Grunt (JS build tool): grunt-typescript, grunt-ts Bower (JS dependency manager) – „typescript“ TypeScript declarations managers: – tsd, nuget IDEs:VisualStudio, Eclipse(TypEcs, eclipse-typescript), WebStrom
TypeScript type definitions (*.d.ts) dependency management tsd:TypeScript Definition manager for DefinitelyTyped – Install it: npm install tsd@next –g – Download latest definitions (recursively) and save dependency to tsd.json: tsd install angular-ui-router --save –r >> written 2 files: - angular-ui/angular-ui-router.d.ts - angularjs/angular.d.tsSearch commit history angular – Install specific revision of angular tsd query angular –history tsd install angular --commit 235f77 –save – Cleanup & reinstall: rm –rf typings tsd reinstall
Demo: Internal modules Declaration in „someLibrary.d.ts“: module ee.iglu.demo { export var publicVar = "Visible to outside"; var privateVar = "Not visible to outside"; export class PublicClass implements PublicType { constructor(public someField: string) { alert("privateVar: "+ privateVar); } } } Usage: /// <reference path="../relative/path/to/someLibrary.d.ts" /> new ee.iglu.demo.PublicClass(„arg");
External modules currently not ES6 compatible – Commonjs (node) File: myModule.ts – /// <reference path="../typings/node.d.ts" /> – import http = module(„http“); – export function myFunction(){…}; In another file in the same folder: – import myModule = module(„./myModule“); – myModule.myFunction(); – AMD (requireJS) – built on topp of commonJS lazy loading Verbose withoutTypeScript
TypeScript: interpreted mode https://github.com/niutech/typescript-compile –demo with angular http://plnkr.co/edit/tahSo5uouPAcemjmXOEv?p=prev ew
TypeScript vs Google Closure Compiler Google Closure Compiler: – Pure JS +Types in JsDoc comments – Focus on optimization, dead-code removal, minification – Less expressive – Warnings from static code analysis
TypeScript vs CoffeScript Common: – CAN compile to JS Different: – JS is NOT valid CoffeScript – Dynamically typed – Completely Different syntax for object literals, functions, rest-args More syntactic sugar – No spec – Doesn't track ES6
TypeScript vs Dart Common: – CAN compile to JS Different: – CAN run on DartVM – Dart stdlib (collections/maps, etc) – JS interop through dart:js lib – Compiled JS is built for specific runtime (no good escape strategy)
Who usesTypeScript? Microsoft Google (Angular team abandoned AtScript for TypeScript) Adobe RedHat LeapMotion Walmart Plantir – Author of eclipse-typescript plugin i have not managed to get working (twice) - my sugestion for Eclipse isTypEcs
TypeScript - conclusion… Still need to know some JS quirks Not yet completely ES6 compatible Non-MS tooling doesn't match yet the level of IDE support offered for Java – it is gradually improving, come and contribute!
TypeScript - …conclusion Modules Enums, Interfaces, Classes, inheritence Generics Optional types (gradual adoption & match forYour comfort level): – no type def-s - inferred type info from primitives, referenced typedefs – some type def-s - most types can be inferred – -noImplicitAny - forces strongly typing High value, low cost improvement over plain JS – safer than JS Solid path to ES6
The end (or start of the new era?) Your comments, thoughts…

TypeScript intro

  • 1.
  • 2.
    Warning & credentials Slidesaremostly based on: –Sander Mak typescript-coding-javascript- without-the-pain –Anders Hejlsberg's video on homepage: www.typescriptlang.org Slides are packed with text –Meant for recalling the presentation people not attending the presentation –You might not want to read the slides ifYou
  • 3.
    Agenda WhyTypeScript Language intro Demos https://github.com/atsu85/TypeScriptPlayField – TypeScriptlanguage features – TypeScript in Angular project (tiny sample) Comparison withTS alternatives Conclusion
  • 4.
    What’s good aboutJS? It’s everywhere – Browsers, servers Huge amount of libraries Flexible procedural and functional
  • 5.
    What’s wrong withJS? Dynamic typing – Can’t do type checking (but lints could help a bit) – Content-assist can’t be automatically provided for IDE’s Lack of modularity (out of the box) Verbose patterns IIFE - Immediately-invoked_function_expression Declaring/extending classes/objects
  • 6.
    Wishlist Scalable HTML5 clientside development – Modularity – Safe Refactoring Type checking Searching for method/filed usages Easily learnable for Java developers Non-invasive – Interop with existing libs – browser support Easy to debug – Clean JS output (also for exit strategy) – Map files (mapping from generated code to originaal source) Long-term vision (Language spec, future standards)
  • 7.
    EcmaScript 6 (ES6) Currentstate – RC2 (March 4, 2015) Release? – "A sixth edition of the standard is currently under development with a target date of June 2015 for completion" ES6 language features with code samples: – https://github.com/lukehoban/es6features
  • 8.
    TypeScript project Superset ofJS(ES5) that compiles to JS – Compiles to ES3/ES5/ES6 – No special runtime dependencies – TypeScript 2.0 goal to be superset of ES6 Website: http://www.typescriptlang.org/ – https://github.com/Microsoft/TypeScript/wiki/Roadmap Microsoft – Anders Hejlsberg (Turbopascal, Delphy, C#,TypeScript) – Working with Flow and Angular(AtScript) teams to become best choice for writing JS OS compiler(also written inTS) and type declarations(JS core, DOM, …) – https://github.com/Microsoft/TypeScript – Apache 2.0 license Uses NodeJS for compiling – Cross platform, no MS dependencies
  • 9.
    TS features fromES6… Classes, inheritance Interfaces Arrow functions aka Lambdas Default parameters, rest parameters (varargs) Template strings
  • 10.
    …TS features fromES6 TS v1.4 (with compile target=ES6, plans to also allow compiling following ES6 features to ES3/ES5) – let, const Roadmap: TS v1.5 – destructuring – for..of, iterators? – unicode – External module compatibility – symbols TS v1.6 – Generators – async/await TS 2.0 "plans" – Superset of ES6
  • 11.
    Getting started Install node InstallTypeScript:´npm install -g typescript´ Rename extension: ´mv mycode.js mycode.ts´ Compile: ´tsc mycode.ts´
  • 12.
    …Getting started -Got compilation error? Resolve errors related to global variables (i.e. globalVar) – declare var globalVar; WhenYou don’t have type information (and don’t want to write it Yourself) – IfYou want type info about the global variable: – See https://github.com/borisyankov/DefinitelyTyped/ – Type definitions for almost 1000 libraries declare var globalVar: someModule.SomeType; Need to reference library or type declarations of the library – /// <reference path=„path/to/my-lib.ts" /> – /// <reference path=„path/to/external-lib-type-info.d.ts" />
  • 13.
    TypeScript language features Syntaxsugar for creating – Classes, interfaces, modules, … Types: – Optional (in code, not in comments) JS isTS – add types when needed – Static Errors at compile time not at runtime – Interfaces, classes or structural Can useType names, but they are not required Checked at compile time, not runtime (unlike with „duck typing“) – Disappear after compiling
  • 14.
    TypeScript vs Java:Classes Similar: – Can implement interfaces – Inheritance – Instance methods/members – Static methods/members – Generics (with type erasure) Different: – No method/constructor overloading – Default & optional parameters – ES6 class syntax (similar to Scala) – Mixins/traits (trivial, but no out-of-the-box syntax as in Scala)
  • 15.
    TypeScript vs Java:Types Object-> any void -> void boolean -> boolean Integer, long, short, … -> number String, char -> string Arrays: – TypeArray[] ->TypeArray[] – primitiveTypeArray[] -> primitiveTypeArray[]
  • 16.
    How it lookslike? var varName:VarType = … ; function functionName(param1: Param1Type): RetrunType { return new RetrunType(param1); } interface IPerson { name: string; getAge(): number;} class Person implements IPerson { constructor(public name: string, private yearOfBirth: number){}; getAge() { // return type can be inferred return new Date().getFullYear() - this.yearOfBirth; // silly demo } }
  • 17.
    Demo: Basics Type annotations Classes,interfaces, functions – Optional/default members – Optional/default function arguments Errors when using missing field/function Type inference – From assignment – From function return value to function return type – From function declared parameter type to argument passed to the function
  • 18.
    Demo: Modules, Interfaces Open-ended –Cancontribute classes/interfaces to a module from another file Can divide code into several files –Can contribute members to interface from another file Very common for jQuery plugins Modules can be imported using var: –var demo = ee.iglu.demo; –var obj = new demo.SomePublicClass();
  • 19.
    Demo: Classes Instance fields Constructor Privatefields – short notation for private fields (or fields with accessors) Static fields Default & optional parameters Inheritence
  • 20.
    Overriding/overloading JS functions can’tbe overloaded! –one function must handle all diferent type combinations, help from: Default and optional parameters Multiple signature definitions
  • 21.
    Tricks with methodsignatures Basically value-agnostic signatures: interface Document { createElement(tagName: „a"): HTMLAnchorElement; createElement(tagName: "div"): HTMLDivElement; } createElement("a").href = „/main“; // OK createElement("div").href = „/main“; // ERROR div doesn't have href
  • 22.
    More useful stuff Arrowfunctions a.k.a. Lambdas Enums Generics – http://www.typescriptlang.org/Playground Mixins/traits – http://www.typescriptlang.org/Handbook#mixins Union types, String interpolation – http://www.typescriptlang.org/Playground: „New Features“ Avoid infering type to „any“ type: – tsc --noImplicitAny superSolid.ts
  • 23.
    TypeScript and externallibs Search forTypeScript declarations for the lib from https://github.com/borisyankov/DefinitelyTyped/ contains type declarations for > 950 libs (~80 jQuery plugins, 30 angular plugins, toastr, moment, fullCalendar, pickadate) http://www.typescriptlang.org/Handbook#writing-dts-files Import type info from type declarations file: /// <reference path=„path/to/external-lib-type-info.d.ts" /> Import type info fromTypeScript source file: /// <reference path=„path/to/my-lib.ts" /> DEMO – UsingTypeScript with AngularJS
  • 24.
    Summary:TypeScriptType System Type inference andstructural typing – Very few type „annotations“ are necessary Formalization of JS types – Static representation of JS dynamic type system Works with existing JS libs – Out of the boxYou can treat any external JS lib object as „any“ type – Declaration files can be writter and maintained separately Not „provably type safe“ – Types reflect intent, but don't provide guarantees Type declaration files can contain mistakes
  • 25.
    Tools:TypeScript Gradle: – Compile: https://github.com/sothmann/typescript-gradle-plugin –Monitor changes: https://github.com/bluepapa32/gradle-watch-plugin Gulp (JS build tool) – Compile: „gulp-type“ (incremental) and gulp-tsc – Watch: gulp.watch() Grunt (JS build tool): grunt-typescript, grunt-ts Bower (JS dependency manager) – „typescript“ TypeScript declarations managers: – tsd, nuget IDEs:VisualStudio, Eclipse(TypEcs, eclipse-typescript), WebStrom
  • 26.
    TypeScript type definitions(*.d.ts) dependency management tsd:TypeScript Definition manager for DefinitelyTyped – Install it: npm install tsd@next –g – Download latest definitions (recursively) and save dependency to tsd.json: tsd install angular-ui-router --save –r >> written 2 files: - angular-ui/angular-ui-router.d.ts - angularjs/angular.d.tsSearch commit history angular – Install specific revision of angular tsd query angular –history tsd install angular --commit 235f77 –save – Cleanup & reinstall: rm –rf typings tsd reinstall
  • 27.
    Demo: Internal modules Declarationin „someLibrary.d.ts“: module ee.iglu.demo { export var publicVar = "Visible to outside"; var privateVar = "Not visible to outside"; export class PublicClass implements PublicType { constructor(public someField: string) { alert("privateVar: "+ privateVar); } } } Usage: /// <reference path="../relative/path/to/someLibrary.d.ts" /> new ee.iglu.demo.PublicClass(„arg");
  • 28.
    External modules currently notES6 compatible – Commonjs (node) File: myModule.ts – /// <reference path="../typings/node.d.ts" /> – import http = module(„http“); – export function myFunction(){…}; In another file in the same folder: – import myModule = module(„./myModule“); – myModule.myFunction(); – AMD (requireJS) – built on topp of commonJS lazy loading Verbose withoutTypeScript
  • 29.
    TypeScript: interpreted mode https://github.com/niutech/typescript-compile –demowith angular http://plnkr.co/edit/tahSo5uouPAcemjmXOEv?p=prev ew
  • 30.
    TypeScript vs GoogleClosure Compiler Google Closure Compiler: – Pure JS +Types in JsDoc comments – Focus on optimization, dead-code removal, minification – Less expressive – Warnings from static code analysis
  • 31.
    TypeScript vs CoffeScript Common: –CAN compile to JS Different: – JS is NOT valid CoffeScript – Dynamically typed – Completely Different syntax for object literals, functions, rest-args More syntactic sugar – No spec – Doesn't track ES6
  • 32.
    TypeScript vs Dart Common: –CAN compile to JS Different: – CAN run on DartVM – Dart stdlib (collections/maps, etc) – JS interop through dart:js lib – Compiled JS is built for specific runtime (no good escape strategy)
  • 33.
    Who usesTypeScript? Microsoft Google (Angularteam abandoned AtScript for TypeScript) Adobe RedHat LeapMotion Walmart Plantir – Author of eclipse-typescript plugin i have not managed to get working (twice) - my sugestion for Eclipse isTypEcs
  • 34.
    TypeScript - conclusion… Stillneed to know some JS quirks Not yet completely ES6 compatible Non-MS tooling doesn't match yet the level of IDE support offered for Java – it is gradually improving, come and contribute!
  • 35.
    TypeScript - …conclusion Modules Enums,Interfaces, Classes, inheritence Generics Optional types (gradual adoption & match forYour comfort level): – no type def-s - inferred type info from primitives, referenced typedefs – some type def-s - most types can be inferred – -noImplicitAny - forces strongly typing High value, low cost improvement over plain JS – safer than JS Solid path to ES6
  • 36.
    The end (orstart of the new era?) Your comments, thoughts…