Ce diaporama a bien été signalé.
Nous utilisons votre profil LinkedIn et vos données d’activité pour vous proposer des publicités personnalisées et pertinentes. Vous pouvez changer vos préférences de publicités à tout moment.

Why TypeScript?

2 114 vues

Publié le

Presented at Web Unleashed on September 16-17, 2015 in Toronto, Canada
More info at www.fitc.ca/webu

Why TypeScript?
with Jeff Francis

OVERVIEW

TypeScript is a type-checked superset of JavaScript that benefits medium-sized to complex JavaScript projects. Why would you want to learn a new language, instead of another JavaScript framework? You have all this existing JavaScript code, so how can you adopt something new without throwing the old stuff out?

This session is about the benefits of using TypeScript on top of JavaScript in your projects, and demonstrate step by step ways of migrating an existing JavaScript project to TypeScript. We will dive into code generated by the compiler and look at resources and tools that make working in TypeScript a pleasurable experience.

OBJECTIVE

To understand when it’s a good idea to use TypeScript.

TARGET AUDIENCE

JavaScript developers.

ASSUMED AUDIENCE KNOWLEDGE

Intermediate JavaScript experience.

FIVE THINGS AUDIENCE MEMBERS WILL LEARN

The basics of TypeScript – types, classes, modules, and functions
How TypeScript’s design makes getting started simple and helps projects
What compiled TypeScript looks like and how to debug
What tools can help take advantage of TypeScript’s type information
How to migrate a JavaScript project to TypeScript

Publié dans : Internet
  • Want to preview some of our plans? You can get 50 Woodworking Plans and a 440-Page "The Art of Woodworking" Book... Absolutely FREE ●●● http://tinyurl.com/yy9yh8fu
       Répondre 
    Voulez-vous vraiment ?  Oui  Non
    Votre message apparaîtra ici
  • Want to preview some of our plans? You can get 50 Woodworking Plans and a 440-Page "The Art of Woodworking" Book... Absolutely FREE ♥♥♥ http://tinyurl.com/yy9yh8fu
       Répondre 
    Voulez-vous vraiment ?  Oui  Non
    Votre message apparaîtra ici
  • Get access to 16,000 woodworking plans, Download 50 FREE Plans... ■■■ http://tinyurl.com/yy9yh8fu
       Répondre 
    Voulez-vous vraiment ?  Oui  Non
    Votre message apparaîtra ici

Why TypeScript?

  1. 1. Why Typescript?
  2. 2. about me… Jeff Francis
  3. 3. you
  4. 4. So what is TypeScript?
  5. 5. a typed superset of JavaScript
  6. 6. a typed superset of JavaScript
  7. 7. it’s JavaScript… but built for more scale
  8. 8. 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
  9. 9. OK, so what does TypeScript do to add scale?
  10. 10. 1. prevents trivial errors 2. makes code more readable 3. discovers the impact of change
  11. 11. 1. prevents trivial errors 2. makes code more readable 3. discovers the impact of change
  12. 12. types find simple bugs
  13. 13. var message = "The inning is: " + inning;
  14. 14. var inning = { label: "Fith", count: 5 } var message = "The inning is: " + inning;
  15. 15. your code already has types
  16. 16. var isBatting = false; var inning = 6; var teamName = "Blue Jays"; var runsRecord = [1, 6, 3];
  17. 17. var isBatting: boolean = false; var inning: number = 6; var teamName: string = "Blue Jays"; var runsRecord: number[] = [1, 6, 3];
  18. 18. JS types are just pretending to be any type
  19. 19. var isBatting: any = false; var inning: any = 6; var teamName: any = "Blue Jays"; var runsRecord: any[] = [1, 6, 3];
  20. 20. var isBatting: boolean = <any> false; var inning: number = <any> false; var teamName: string = <any> false; var runsRecord: number[] = <any> false;
  21. 21. var pitch = function(type) { if (type == "fastball") return 170.5; else return 123.9; };
  22. 22. var pitch = function(type: string): number { if (type == "fastball") return 170.5; else return 123.9; };
  23. 23. var pitch = function(type: string): boolean { if (type == "fastball") return true; else return false; }; var x = pitch("curve"); console.log(x – 10); --error
  24. 24. implicit conversions are evil
  25. 25. (0 == []) == true (!!0 == !![]) == false 0 + [] == "0" ???
  26. 26. this
  27. 27. ... this.catch().then(function(ball) { this.throw(ball); });
  28. 28. var _this = this; this.catch().then(function(ball) { _this.throw(ball); });
  29. 29. ... this.catch().then((ball) => { this.throw(ball); });
  30. 30. prototypes to classes
  31. 31. var Player = function(jerseyName, fielding) { this.jerseyName = jerseyName; this.currentPosition = fielding; } Player.prototype.throw = function() { console.log("Throwing"); } var jeffFrancis = new Player("FRANCIS", "P");
  32. 32. 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");
  33. 33. 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");
  34. 34. var
  35. 35. var player = oldPlayer; for (var i = 0; i < trades.length; i++) { var player = trades[i]; trade(player); } expect(player).toBe(trades[trades.length -1]);
  36. 36. var player = oldPlayer; for (var i = 0; i < trades.length; i++) { let player = trades[i]; trade(player); } expect(player).toBe(oldPlayer);
  37. 37. for (var i = 0; i < trades.length; i++) { player = trades[i]; trade(player); }
  38. 38. var LINEUP_SIZE = 9; LINEUP_SIZE = 10;
  39. 39. const LINEUP_SIZE = 9; LINEUP_SIZE = 10; … error
  40. 40. 1. prevents trivial errors 2. makes code more readable 3. discovers the impact of change
  41. 41. types add reader context
  42. 42. function placePlayer(player, role) { PlayerManager.add(player, role); } … placePlayer("FRANCIS", "P"); placePlayer(new Player("FRANCIS"), 1); placePlayer({ name: "Francis" }, 1);
  43. 43. 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);
  44. 44. typed JSDoc isn’t as good as actual types /* @param {!Array.<!number>} mn Incoming tanget of last point. */
  45. 45. … var players = $(selected)
  46. 46. $(selector) $(element) $(element array) $(html) $(callback) $($)
  47. 47. building with modules is now easier
  48. 48. <script src="baseball.js"></script>
  49. 49. document.createElement("script")
  50. 50. most must compile…
  51. 51. if (!namespace) namespace = {}
  52. 52. module Baseball { class Player { jerseyName: string; currentPosition: string; constructor(jerseyName: string, fielding: string) { this.jerseyName = jerseyName; this.currentPosition = fielding; } throw(ball) { console.log("throwing"); } } }
  53. 53. 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;
  54. 54. let and const also help with readability
  55. 55. it is easier to read when you can play with the code
  56. 56. but...
  57. 57. 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
  58. 58. 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); } }
  59. 59. closures and types work together
  60. 60. 1. prevents trivial errors 2. makes code more readable 3. discovers the impact of change
  61. 61. types help you change with confidence
  62. 62. “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
  63. 63. “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
  64. 64. demo
  65. 65. so how to start using this?
  66. 66. TypeScript not not JavaScript
  67. 67. TypeScript is aligned with ES6
  68. 68. using d.ts we can type existing .js
  69. 69. 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.layoutmanage r 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.datetimepi cker 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
  70. 70. 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; …
  71. 71. 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
  72. 72. demo
  73. 73. this is possible because of gradual typing
  74. 74. interface Findable { whereAreYou(): string; }; class Player implements Findable { ... whereAreYou() { return "Playing Baseball"; } }; var player: Findable = new Player(); player.whereAreYou();
  75. 75. interface Findable { whereAreYou(): string; }; class Player { ... whereAreYou() { return "Playing Baseball"; } }; var player: Findable = new Player(); player.whereAreYou();
  76. 76. class Player { ... whereAreYou() { return "Playing Baseball"; } }; interface Findable { whereAreYou(): string; }; var player: Findable = new Player(); player.whereAreYou();
  77. 77. late interfaces let you write simpler types SimpleBeanFactoryAwareAspectInstanceFactory AbstractSingletonProxyFactoryBean http://www.quora.com/What-are-the-most-ridiculous-Java- class-names-from-real-code
  78. 78. late interfaces help with partial data and object literals
  79. 79. demo
  80. 80. so how do I do it with my code?
  81. 81. if your module is stable use d.ts to add types
  82. 82. if you’re still in flux rename .js to .ts and fix errors then migrate to new structures
  83. 83. demo
  84. 84. TypeScript works with others
  85. 85. jQuery Angular React <JSX>
  86. 86. /// <reference path="react.d.ts" /> interface PlayerProps { name: string; } class Batter extends React.Component<PlayerProps, {}> { render() { return ( <div>{this.props.name} swings!</div> ); } }
  87. 87. Grunt Gulp Make
  88. 88. 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
  89. 89. VIM Emacs VisualStudio others…
  90. 90. TypeScript is easy to try
  91. 91. Resources Playground http://www.typescriptlang.org/ Tutorial http://www.typescriptlang.org/Tutorial Type Definitions https://github.com/borisyankov/DefinitelyTyped

×