61
TypeScript coding JavaScript without the pain @Sander_Mak Luminis Technologies

TypeScript: coding JavaScript without the pain

Embed Size (px)

DESCRIPTION

Slides accompanying the JavaOne 2014 presentation on TypeScript

Citation preview

Page 1: TypeScript: coding JavaScript without the pain

TypeScript coding JavaScript without the pain

@Sander_Mak Luminis Technologies

Page 2: TypeScript: coding JavaScript without the pain

INTRO@Sander_Mak: Senior Software Engineer at

Author:Dutch Java Magazine

blog @ branchandbound.netSpeaker:

Page 3: TypeScript: coding JavaScript without the pain

AGENDAWhy TypeScript? Language introduction / live-coding TypeScript and Angular Comparison with TS alternatives Conclusion

Page 4: TypeScript: coding JavaScript without the pain

WHAT'S WRONG WITH JAVASCRIPT?

Dynamic typing Lack of modularity Verbose patterns (IIFE)

Page 5: TypeScript: coding JavaScript without the pain

WHAT'S WRONG WITH JAVASCRIPT?

Dynamic typing Lack of modularity Verbose patterns (IIFE)

In short: JavaScript development scales badly

Page 6: TypeScript: coding JavaScript without the pain

WHAT'S GOOD ABOUT JAVASCRIPT?

It's everywhere Huge amount of libraries Flexible

Page 7: TypeScript: coding JavaScript without the pain

WISHLISTScalable HTML5 clientside development Modular development Easily learnable for Java developers Non-invasive (existing libs, browser support) Long-term vision Clean JS output (exit strategy)

Page 8: TypeScript: coding JavaScript without the pain

WISHLISTScalable HTML5 clientside development Modular development Easily learnable for Java developers Non-invasive (existing libs, browser support) Long-term vision Clean JS output (exit strategy)

✓✓✓✓✓✓

Page 9: TypeScript: coding JavaScript without the pain
Page 10: TypeScript: coding JavaScript without the pain

2.0 licensed

Page 11: TypeScript: coding JavaScript without the pain

2.0 licensed

Page 12: TypeScript: coding JavaScript without the pain

TYPESCRIPTSuperset of JavaScript Optionally typed Compiles to ES3/ES5 No special runtime 1.0 in April 2014, future ES6 alignment

Page 13: TypeScript: coding JavaScript without the pain

TYPESCRIPT

In short: Lightweight productivity booster

Superset of JavaScript Optionally typed Compiles to ES3/ES5 No special runtime 1.0 in April 2014, future ES6 alignment

Page 14: TypeScript: coding JavaScript without the pain

GETTING STARTED

$ npm install -g typescript $ mv mycode.js mycode.ts $ tsc mycode.ts

Page 15: TypeScript: coding JavaScript without the pain

GETTING STARTED

$ npm install -g typescript $ mv mycode.js mycode.ts $ tsc mycode.ts

May even find problems in existing JS!

Page 16: TypeScript: coding JavaScript without the pain

OPTIONAL TYPESType annotations> var a = 123 > a.trim() !

TypeError: undefined is not a function

JS

> var a: string = 123 > a.trim() !

Cannot convert 'number' to 'string'.

TS

runtime

compile-time

Page 17: TypeScript: coding JavaScript without the pain

OPTIONAL TYPESType annotations> var a = 123 > a.trim() !

TypeError: undefined is not a function

JS

> var a: string = 123 > a.trim() !

Cannot convert 'number' to 'string'.

TS

Type inference

Types dissapear at runtime

> var a = 123 > a.trim() !

The property 'trim' does not exist on value of type 'number'.

Page 18: TypeScript: coding JavaScript without the pain

numberboolean string type[]any void

Object void boolean integer long short ...

String char

Type[]

OPTIONAL TYPES

Page 19: TypeScript: coding JavaScript without the pain

OPTIONAL TYPESTypes are structural rather than nominal

var find: (elem: string, elems: string[]) => string = function(elem, elems) { .. }

TypeScript has function types:

Page 20: TypeScript: coding JavaScript without the pain

OPTIONAL TYPESTypes are structural rather than nominal

var find: (elem: string, elems: string[]) => string = function(elem, elems) { .. }

TypeScript has function types:

Page 21: TypeScript: coding JavaScript without the pain

DEMO: OPTIONAL TYPES

code

Code: http://bit.ly/tscode

Page 22: TypeScript: coding JavaScript without the pain

INTERFACESinterface MyInterface { // Call signature (param: number): string member: number optionalMember?: number myMethod(param: string): void } !

var instance: MyInterface = ... instance(1)

Page 23: TypeScript: coding JavaScript without the pain

INTERFACES

Use them to describe data returned in REST calls

$.getJSON('user/123').then((user: User) => { showProfile(user.details) }

Page 24: TypeScript: coding JavaScript without the pain

INTERFACES

TS interfaces are open-ended:

interface JQuery { appendTo(..): .. .. }

interface JQuery { draggable(..): .. .. }jquery.d.ts jquery.ui.d.ts

Page 25: TypeScript: coding JavaScript without the pain

OPTIONAL TYPES: ENUMS

enum Language { TypeScript, Java, JavaScript } !

var lang = Language.TypeScript var ts = Language[0] ts === "TypeScript"

enum Language { TypeScript = 1, Java, JavaScript } !

var ts = Language[1]

Page 26: TypeScript: coding JavaScript without the pain

GOING ALL THE WAYForce explicit typing with noImplicitAny

$ tsc --noImplicitAny noimplicitany.ts

var ambiguousType; !

ambiguousType = 1 ambiguousType = "text" noimplicitany.ts

Page 27: TypeScript: coding JavaScript without the pain

GOING ALL THE WAYForce explicit typing with noImplicitAny

$ tsc --noImplicitAny noimplicitany.ts

var ambiguousType; !

ambiguousType = 1 ambiguousType = "text" noimplicitany.ts

error TS7005: Variable 'ambiguousType' implicitly has an 'any' type.

Page 28: TypeScript: coding JavaScript without the pain

Can implement interfaces Inheritance Instance methods/members Static methods/members

TYPESCRIPT CLASSES

Single constructor Default/optional parameters ES6 class syntax

similar

different

Page 29: TypeScript: coding JavaScript without the pain

DEMO: TYPESCRIPT CLASSES

code

Code: http://bit.ly/tscode

Page 30: TypeScript: coding JavaScript without the pain

ARROW FUNCTIONSImplicit return No braces for single expression Part of ES6

Page 31: TypeScript: coding JavaScript without the pain

ARROW FUNCTIONSImplicit return No braces for single expression Part of ES6

function(arg1) { return arg1.toLowerCase(); }

Page 32: TypeScript: coding JavaScript without the pain

ARROW FUNCTIONSImplicit return No braces for single expression Part of ES6

function(arg1) { return arg1.toLowerCase(); }

(arg1) => arg1.toLowerCase();

Page 33: TypeScript: coding JavaScript without the pain

ARROW FUNCTIONSImplicit return No braces for single expression Part of ES6

function(arg1) { return arg1.toLowerCase(); }

(arg1) => arg1.toLowerCase();

Lexically-scoped this (no more 'var that = this')

Page 34: TypeScript: coding JavaScript without the pain

DEMO: ARROW FUNCTIONS

code

Code: http://bit.ly/tscode

Page 35: TypeScript: coding JavaScript without the pain

TYPE DEFINITIONS

Ambient declarations Any-type :( Type definitions lib.d.ts Separate compilation:

tsc --declaration file.ts

How to integrate existing JS code?

Page 36: TypeScript: coding JavaScript without the pain

TYPE DEFINITIONSDefinitelyTyped.orgCommunity provided .d.ts files for popular JS libs

Ambient declarations Any-type :( Type definitions lib.d.ts Separate compilation:

tsc --declaration file.ts

How to integrate existing JS code?

Page 37: TypeScript: coding JavaScript without the pain

module StorageModule { export interface Storage { store(content: string): void } ! var privateKey = 'storageKey'; export class LocalStorage implements Storage { store(content: string): void { localStorage.setItem(privateKey, content); } } ! export class DevNullStorage implements Storage { store(content: string): void { } } } !var storage: StorageModule.Storage = new StorageModule.LocalStorage(); storage.store('testing');

INTERNAL MODULES

Page 38: TypeScript: coding JavaScript without the pain

module StorageModule { export interface Storage { store(content: string): void } ! var privateKey = 'storageKey'; export class LocalStorage implements Storage { store(content: string): void { localStorage.setItem(privateKey, content); } } ! export class DevNullStorage implements Storage { store(content: string): void { } } } !var storage: StorageModule.Storage = new StorageModule.LocalStorage(); storage.store('testing');

INTERNAL MODULES

Page 39: TypeScript: coding JavaScript without the pain

module StorageModule { export interface Storage { store(content: string): void } ! var privateKey = 'storageKey'; export class LocalStorage implements Storage { store(content: string): void { localStorage.setItem(privateKey, content); } } ! export class DevNullStorage implements Storage { store(content: string): void { } } } !var storage: StorageModule.Storage = new StorageModule.LocalStorage(); storage.store('testing');

INTERNAL MODULES

Page 40: TypeScript: coding JavaScript without the pain

module StorageModule { export interface Storage { store(content: string): void } ! var privateKey = 'storageKey'; export class LocalStorage implements Storage { store(content: string): void { localStorage.setItem(privateKey, content); } } ! export class DevNullStorage implements Storage { store(content: string): void { } } } !var storage: StorageModule.Storage = new StorageModule.LocalStorage(); storage.store('testing');

INTERNAL MODULES

Page 41: TypeScript: coding JavaScript without the pain

INTERNAL MODULES

TS internal modules are open-ended:!

module Webshop { export class Cart { .. } }

/// <reference path="cart.ts" /> module Webshop { export class Catalog { .. } }cart.ts main.ts

Page 42: TypeScript: coding JavaScript without the pain

INTERNAL MODULES

TS internal modules are open-ended:!

module Webshop { export class Cart { .. } }

/// <reference path="cart.ts" /> module Webshop { export class Catalog { .. } }cart.ts main.ts

Can be hierarchical:module Webshop.Cart.Backend { ... }

Page 43: TypeScript: coding JavaScript without the pain

INTERNAL MODULES

TS internal modules are open-ended:!

module Webshop { export class Cart { .. } }

/// <reference path="cart.ts" /> module Webshop { export class Catalog { .. } }cart.ts main.ts

Can be hierarchical:module Webshop.Cart.Backend { ... }

Combine modules:$ tsc --out main.js main.ts

Page 44: TypeScript: coding JavaScript without the pain

DEMO: PUTTING IT ALL TOGETHER

code

Code: http://bit.ly/tscode

Page 45: TypeScript: coding JavaScript without the pain

EXTERNAL MODULES

CommonJS

Asynchronous Module Definitions

$ tsc --module common main.ts

$ tsc --module amd main.ts

Combine with module loader

Page 46: TypeScript: coding JavaScript without the pain

EXTERNAL MODULES

'Standards-based', use existing external modules Automatic dependency management Lazy loading AMD verbose without TypeScript Currently not ES6-compatible

Page 47: TypeScript: coding JavaScript without the pain

DEMO

+ +

=

Page 48: TypeScript: coding JavaScript without the pain

DEMO: TYPESCRIPT AND ANGULAR

code

Code: http://bit.ly/tscode

Page 49: TypeScript: coding JavaScript without the pain

BUILDING TYPESCRIPT

$ tsc -watch main.ts

grunt-typescript grunt-ts

gulp-type (incremental) gulp-tsc

Page 50: TypeScript: coding JavaScript without the pain

TOOLINGIntelliJ IDEA WebStorm

plugin

Page 51: TypeScript: coding JavaScript without the pain

TYPESCRIPT vs ES6 HARMONY

Complete language + runtime overhaul More features: generators, comprehensions, object literals Will take years before widely deployed No typing (possible ES7)

Page 52: TypeScript: coding JavaScript without the pain

TYPESCRIPT vs COFFEESCRIPT

Also a compile-to-JS language More syntactic sugar, still dynamically typed JS is not valid CoffeeScript No spec, definitely no Anders Hejlsberg... Future: CS doesn't track ECMAScript 6 !

Page 53: TypeScript: coding JavaScript without the pain

TYPESCRIPT vs DART

Dart VM + stdlib (also compile-to-JS) Optionally typed Completely different syntax & semantics than JS JS interop through dart:js library ECMA Dart spec

Page 54: TypeScript: coding JavaScript without the pain

TYPESCRIPT vs CLOSURE COMPILER

Pure JS Types in JsDoc comments Less expressive Focus on optimization, dead-code removal

Google Closure Compiler

Page 55: TypeScript: coding JavaScript without the pain

WHO USES TYPESCRIPT?

(duh)

Page 56: TypeScript: coding JavaScript without the pain

CONCLUSION

Internal modules Classes/Interfaces Some typing

External modules Type defs More typing

Generics Type defs -noImplicitAny

Page 57: TypeScript: coding JavaScript without the pain

CONCLUSION

TypeScript allows for gradual adoption

Internal modules Classes/Interfaces Some typing

External modules Type defs More typing

Generics Type defs -noImplicitAny

Page 58: TypeScript: coding JavaScript without the pain

CONCLUSION

Still need to know some JS quirks Current compiler slowish (faster one in the works) External module syntax not ES6-compatible (yet) Non-MS tooling lagging a bit

Some downsides:

Page 59: TypeScript: coding JavaScript without the pain

CONCLUSION

High value, low cost improvement over JavaScript Safer and more modular Solid path to ES6

Page 60: TypeScript: coding JavaScript without the pain

MORE TALKS

@Sander_Mak Luminis Technologies

TypeScript: Wednesday, 11:30 AM, same room !Akka & Event-sourcing Wednesday, 8:30 AM, same room

Page 61: TypeScript: coding JavaScript without the pain

RESOURCES

@Sander_Mak Luminis Technologies

Code: http://bit.ly/tscode !

Learn: www.typescriptlang.org/Handbook