Why TypeScript?

92
Why Typescript?

Transcript of Why TypeScript?

Why Typescript?

about me…Jeff Francis

you

So what is TypeScript?

a typed superset of JavaScript

a typed superset of JavaScript

it’s JavaScript…but built for more scale

coffeescript Dart Coco LiveScript IcedCoffeeScript Parsec Contracts.coffee Uberscript ToffeeScript Caffeine heap.coffee EmberScript Jack move Moescript pogoscript LispyScript wisp Hot Sibilant ki jisp Ham GorillaScript RedScript Daonode LiteScript ColaScript Taijilang MoonScript Earl Khepri Spider CirruScript Pallet TLC CokeScript imba TeJaS asm.js JavaScript++ MileScript Mascara Roy Elm JSX Este.js Swym Typecast.js PureScript AtScript Flow Streamline.js mobl StratifiedJS NarrativeJS jwacs Wind.js TameJS Continuation.js Kal JSPipe promiseLand ContextJS Objective-J Mochiscript jangaroo Flapjax jLang Restrict TIScript Six js-- Latte JSX Ruby Python Erlang Perl Java/JVM Scala C# F# Lisp Scheme ClojureScript Ocamljs Haskell Smalltalk C/C++ Basic Pascal Go SQL PHP. etc…

source: https://github.com/jashkenas/coffeescript/wiki/List-of-languages-that-compile-to-JS

OK, so what does TypeScript do to add scale?

1. prevents trivial errors2. makes code more readable3. discovers the impact of change

1. prevents trivial errors2. makes code more readable3. discovers the impact of change

types find simple bugs

var message = "The inning is: " + inning;

var inning = { label: "Fith", count: 5}var message = "The inning is: " + inning;

your code already has types

var isBatting = false;var inning = 6;var teamName = "Blue Jays";var runsRecord = [1, 6, 3];

var isBatting: boolean = false;var inning: number = 6;var teamName: string = "Blue Jays";var runsRecord: number[] = [1, 6, 3];

JS types are just pretending to be any type

var isBatting: any = false;var inning: any = 6;var teamName: any = "Blue Jays";var runsRecord: any[] = [1, 6, 3];

var isBatting: boolean = <any> false;var inning: number = <any> false;var teamName: string = <any> false;var runsRecord: number[] = <any> false;

var pitch = function(type) { if (type == "fastball") return 170.5; else return 123.9;};

var pitch = function(type: string): number { if (type == "fastball") return 170.5; else return 123.9;};

var pitch = function(type: string): boolean { if (type == "fastball") return true; else return false;};var x = pitch("curve");console.log(x – 10); --error

implicit conversions are evil

(0 == []) == true (!!0 == !![]) == false

0 + [] == "0"???

this

...this.catch().then(function(ball) { this.throw(ball);});

var _this = this;this.catch().then(function(ball) { _this.throw(ball);});

...this.catch().then((ball) => { this.throw(ball);});

prototypes to classes

var Player = function(jerseyName, fielding) { this.jerseyName = jerseyName; this.currentPosition = fielding; }Player.prototype.throw = function() { console.log("Throwing"); }

var jeffFrancis = new Player("FRANCIS", "P");

class Player { jerseyName: string; currentPosition: string; constructor(jerseyName: string, fielding: string) { this.jerseyName = jerseyName; this.currentPosition = fielding; } throw(ball) { console.log("throwing"); }}var jeffFrancis = new Player("FRANCIS", "P");

class Player extends Person { jerseyName: string; currentPosition: string; constructor(jerseyName: string, fielding: string) { super(); this.jerseyName = jerseyName; this.currentPosition = fielding; } throw(ball) { console.log("throwing"); }}var jeffFrancis = new Player("FRANCIS", "P");

var

var player = oldPlayer;for (var i = 0; i < trades.length; i++) { var player = trades[i]; trade(player);}

expect(player).toBe(trades[trades.length -1]);

var player = oldPlayer;for (var i = 0; i < trades.length; i++) { let player = trades[i]; trade(player);}

expect(player).toBe(oldPlayer);

for (var i = 0; i < trades.length; i++) { player = trades[i]; trade(player);}

var LINEUP_SIZE = 9;LINEUP_SIZE = 10;

const LINEUP_SIZE = 9;LINEUP_SIZE = 10; … error

1. prevents trivial errors2. makes code more readable3. discovers the impact of change

types add reader context

function placePlayer(player, role) { PlayerManager.add(player, role);}…placePlayer("FRANCIS", "P");placePlayer(new Player("FRANCIS"), 1);placePlayer({ name: "Francis" }, 1);

enum Fielding { B1, B2, B3, SS, C, LF, CF, RF, P};

function placePlayer(player: string, role: Fielding) { PlayerManager.add(player, role);}…placePlayer("FRANCIS", Fielding.P);

typed JSDoc isn’t as good as actual types

/* @param {!Array.<!number>} mn Incoming tanget of last point. */

$

…var players = $(selected)

$(selector)$(element)

$(element array)$(html)

$(callback)$($)

building with modules is now easier

<script src="baseball.js"></script>

document.createElement("script")

most must compile…

if (!namespace) namespace = {}

module Baseball { class Player { jerseyName: string; currentPosition: string; constructor(jerseyName: string, fielding: string) { this.jerseyName = jerseyName; this.currentPosition = fielding; } throw(ball) { console.log("throwing"); } }}

import Person = require("Person");module Baseball { class Player extends Person { jerseyName: string; currentPosition: string; constructor(jerseyName: string, fielding: string) { super(); this.jerseyName = jerseyName; this.currentPosition = fielding; } throw(ball) { console.log("throwing"); } }}export = Baseball;

let and const also help with readability

it is easier to read when you can play with the code

but...

File file = new File("some_file.txt");

BufferedReader reader =

new BufferedReader(new FileReader(file));

String line = reader.readLine();

while (line != null) {

System.out.println(line.toUpperCase());

line = reader.readLine();

}

reader.close();

File.open("some_file.txt") do |file|

file.readlines.each do |line|

puts line.upcase

end

end

import java.util.Comparator;public class PlayerComparator implements Comparator { @Override public int compare(Player p1, Player p2) { String name1 = p1.getName(); String name2 = p2.getName(); return name1.compareTo(name2); }}

closures and types work together

1. prevents trivial errors2. makes code more readable3. discovers the impact of change

types help you change with confidence

“When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call

that bird a duck.”

- James Whitcomb Riley

“When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call

that bird a duck.”

- James Whitcomb Riley

demo

so how to start using this?

TypeScript not not JavaScript

TypeScript is aligned with ES6

using d.ts we can type existing .js

acc-wizard

accounting

ace

acl

acorn

add2home

adm-zip

alertify

alt

amcharts

amplifyjs

amqp-rpc

amqplib

angular-agility

angular-bootstrap-lightbox

angular-dynamic-locale

angular-file-upload

angular-formly

angular-gettext

angular-growl-v2

angular-hotkeys

angular-http-auth

angular-idle

angular-jwt

angular-local-storage

angular-localForage

angular-material

angular-meteor

angular-notifications

angular-notify

angular-odata-resources

angular-protractor

angular-scenario

angular-scroll

angular-signalr-hub

angular-spinner

angular-storage

angular-toasty

angular-translate

angular-ui-bootstrap

angular-ui-router

angular-ui-scroll

angular-ui-sortable

angular-ui-tree

angular-wizard

angular.throttle

angular2

angularLocalStorage

angularfire

angularjs-toaster

angularjs

angulartics

animation-frame

ansi-styles

ansicolors

any-db-transaction

any-db

api-error-handler

apn

appframework

applicationinsights

arbiter

arcgis-js-api

archiver

archy

asciify

aspnet-identity-pw

assert

assertion-error

async

asyncblock

atmosphere

atom-keymap

atom

atpl

auth0.lock

auth0.widget

auth0

auto-launch

autobahn

autoprefixer-core

aws-sdk

axios

azure-mobile-services-client

backbone-associations

backbone-relational

backbone.layoutmanager

backbone.paginator

backbone.radio

backbone

backgrid

baconjs

bardjs

batch-stream

bcrypt

better-curry

bgiframe

big-integer

big.js

bigint

bigscreen

bingmaps

bitwise-xor

bl

blob-stream

blocks

bluebird-retry

bluebird

blueimp-md5

body-parser

boom

bootbox

bootstrap-notify

bootstrap-slider

bootstrap-touchspin

bootstrap.datepicker

bootstrap.paginator

bootstrap.timepicker

bootstrap.v3.datetimepicker

bootstrap

bowser

box2d

breeze

browser-harness

browser-sync

browserify

bucks

buffer-equal

buffers

bufferstream

bunyan-logentries

bunyan-prettystream

bunyan

business-rules-engine

byline

calq

camel-case

camljs

canvasjs

casperjs

chai-as-promised

chai-datetime

chai-fuzzy

chai-http

chai-jquery

chai-subset

chai

chalk

chance

change-case

chartjs

checksum

cheerio

chocolatechipjs

chokidar

chosen

chroma-js

chrome

chui

circular-json

ckeditor

classnames

cli-color

clone

codemirror

coffeeify

colorbrewer

colors

cometd

commander

compare-version

compression

configstore

connect-flash

connect-modrewrite

connect-slashes

consolidate

constant-case

content-type

contextjs

interface JQueryStatic { ajax(settings: JQueryAjaxSettings): JQueryXHR; ajax(url: string, settings?: JQueryAjaxSettings): JQueryXHR; … (selector: string, context?: Element|JQuery): JQuery; (element: Element): JQuery; (elementArray: Element[]): JQuery; (callback: (jQueryAlias?: JQueryStatic) => any): JQuery; (object: {}): JQuery; (object: JQuery): JQuery; (): JQuery; …

interface Node extends EventTarget { nodeType: number; previousSibling: Node; localName: string; namespaceURI: string; textContent: string; parentNode: Node; nextSibling: Node; nodeValue: string; lastChild: Node; childNodes: NodeList; nodeName: string; ownerDocument: Document; attributes: Attr[];…

lib.d.ts is over 7K LOC of types

demo

this is possible because of gradual typing

interface Findable { whereAreYou(): string;};class Player implements Findable { ... whereAreYou() { return "Playing Baseball"; }};var player: Findable = new Player();player.whereAreYou();

interface Findable { whereAreYou(): string;};class Player { ... whereAreYou() { return "Playing Baseball"; }};var player: Findable = new Player();player.whereAreYou();

class Player { ... whereAreYou() { return "Playing Baseball"; }};interface Findable { whereAreYou(): string;};var player: Findable = new Player();player.whereAreYou();

late interfaces let you write simpler types

SimpleBeanFactoryAwareAspectInstanceFactoryAbstractSingletonProxyFactoryBean

http://www.quora.com/What-are-the-most-ridiculous-Java-class-names-from-real-code

late interfaces help with partial data and object literals

demo

so how do I do it with my code?

if your module is stableuse d.ts to add types

if you’re still in fluxrename .js to .ts and fix errors

then migrate to new structures

demo

TypeScript works with others

jQueryAngular

React <JSX>

/// <reference path="react.d.ts" />

interface PlayerProps { name: string;}

class Batter extends React.Component<PlayerProps, {}> { render() { return ( <div>{this.props.name} swings!</div> ); }}

GruntGulpMake

TYPESCRIPT:=node_modules/.bin/tsc$(TYPESCRIPT_TIMESTAMP): $(TYPESCRIPT_SRC) $(TYPESCRIPT_DTS_SRC)

@echo "Compiling typescript..."@$(TYPESCRIPT) $^ --outDir $(JS_PATH) --sourceMap \

--sourceRoot ../src --noImplicitAny --target ES5 --declaration

VIMEmacs

VisualStudioothers…

TypeScript is easy to try

ResourcesPlayground http://www.typescriptlang.org/

Tutorial http://www.typescriptlang.org/Tutorial

Type Definitions https://github.com/borisyankov/DefinitelyTyped