TypeScript intro
-
Upload
ats-uiboupin -
Category
Software
-
view
191 -
download
1
Transcript of TypeScript intro
Warning & credentials
Slides are 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 ifYouare listening
Agenda
Why TypeScript
Language intro
Demos https://github.com/atsu85/TypeScriptPlayField
– TypeScript language features
– TypeScript in Angular project (tiny sample)
Comparison with TS 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
WishlistScalable HTML5 client side development– Modularity
– Safe RefactoringType 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 projectSuperset 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 in TS) 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 ES6TS 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
Install TypeScript: ´npm install -g typescript´
Rename extension: ´mv mycode.js mycode.ts´
Compile: ´tsc mycode.ts´
…Getting started - Gotcompilation 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 itYourself)
– 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 is TS – add types when needed
– StaticErrors at compile time not at runtime
– Interfaces, classes or structuralCan use Type 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 fileCan divide code into several files
–Can contribute members to interface fromanother 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 stuffArrow 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 libsSearch for TypeScript declarations for the lib fromhttps://github.com/borisyankov/DefinitelyTyped/
contains type declarations for > 950 libs (~80 jQueryplugins, 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 from TypeScript source file:/// <reference path=„path/to/my-lib.ts" />
DEMO– Using TypeScript with AngularJS
Summary: TypeScript TypeSystem
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: TypeScriptGradle:– 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 dependencyto 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 angulartsd query angular –historytsd install angular --commit 235f77 –save
– Cleanup & reinstall:rm –rf typingstsd reinstall
Demo: Internal modulesDeclaration 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 commonJSlazy loading
Verbose without TypeScript
TypeScript: interpreted mode
https://github.com/niutech/typescript-compile–demo with angular
http://plnkr.co/edit/tahSo5uouPAcemjmXOEv?p=preview
TypeScript vs Google ClosureCompiler
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 Dart VM
–Dart stdlib (collections/maps, etc)
– JS interop through dart:js lib
– Compiled JS is built for specific runtime (no good escapestrategy)
Who uses TypeScript?
Microsoft
Google (Angular team abandoned AtScript forTypeScript)
Adobe
RedHat
LeapMotion
Walmart
Plantir– Author of eclipse-typescript plugin
i have not managed to get working (twice) - my sugestion for Eclipseis TypEcs
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 - …conclusionModules
Enums, Interfaces, Classes, inheritence
Generics
Optional types (gradual adoption & match forYourcomfort 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