Upgrade to Pro — share decks privately, control downloads, hide ads and more …

TypeScript And Other Post-JS Languages

TypeScript And Other Post-JS Languages

JS shortcomings, alternatives and TypeScript compared.

Avatar for Federico Ceccatto

Federico Ceccatto

January 17, 2014
Tweet

Other Decks in Programming

Transcript

  1. “ ” JavaScript is a terrible language. Introduction | P

    r e m i s e | C h a l l e n g e r s | T y p e S c r i p t 2 - Me, every time we touch a .js file.
  2. Turns out some people agree… But if Google’s suggestions are

    anything to go by, most people are actually concerned with figuring out how to do things in JavaScript rather than complain about it. Press any letter after “javascript_“ and most likely Google will suggest a call for help. The sheer amount of people struggling with basic programming problems or core features of the language is simply staggering. 3 Introduction | Premise | Challengers | TypeScript
  3. …in fact, I’m preaching to the choir. Slightly less reviled

    than PHP … but that’s not saying much. Yet whatever you may think of the TIOBE index, the language leapt from the 21st place in 1999 to the ninth in 2004, and has stayed there since. A quote from the TIOBE site explains their method: The TIOBE Programming Community index is an indicator of the popularity of programming languages. The index is updated once a month. The ratings are based on the number of skilled engineers world-wide, courses and third party vendors. Popular search engines such as Google, Bing, Yahoo!, Wikipedia, Amazon, YouTube and Baidu are used to calculate the ratings. Observe that the TIOBE index is not about the best programming language or the language in which most lines of code have been written. JavaScript keeps company with industry titans such as C, Java, Objective-C, C++, C#, PHP , Visual Basic and Python. 4 Introduction | Premise | Challengers | TypeScript
  4. Some people try to make it work. Douglas Crockford’s “JavaScript:

    The Good Parts” is Amazon’s best-selling book on JavaScript programming. The author currently serves as PayPal’s senior JavaScript architect and is a General Assembly member of the ECMAScript committee on behalf of eBay. He also specified and popularized RFC 4627 (the JSON data format). Additionally, he was driven nuts by Nintendo© in a convoluted attempt to port and censor Maniac Mansion™ for a NES release. Also, I spelt “committee” wrong six times before giving up and looking it up online. 5 Introduction | Premise | Challengers | TypeScript
  5. Some people laugh about it. Gary Bernhardt’s “WAT” talk at

    Destroy all Software both teaches and jokes about the nonsensical coercion rules and primitive operator overloads in the language. A must-see for anyone even slightly interested about web development: https://www.destroyallsoftware.com/talks/wat 6 Introduction | Premise | Challengers | TypeScript
  6. Some people bitch about it. Zed A. Shaw tells it

    like it is: “[…] we’re stuck with this crap for now… and despite all this stuff, we make amazing things. It’s way harder than it should be though, because in the back of our heads –at least in the back of my head, there’s this little voice that’s constantly whispering ‘bullshit… buuullshit’” 7 Introduction | Premise | Challengers | TypeScript
  7. 8 Introduction | Premise | Challengers | TypeScript Most of

    us are just baffled by it. function sorter(a,b) { if(a < b) return -1; if(a > b) return 1; return 0; } [10, '9', 8, 'seven', 6, 'all my fives', 4, '3', 2, '!!!11one', 0].sort(sorter) // [2, 8, "!!!11one", 0, "3", "9", 10, "all my fives", "seven", 4, 6] Opera 12 // ["all my fives", 0, "!!!11one", "seven", 2, "3", 4, 6, 8, "9", 10] Chrome // [8, "9", 10, "seven", 6, "all my fives", 2, "3", 4, "!!!11one", 0] FF // [2, "3", 8, "9", 10, "seven", 6, "all my fives", 4, "!!!11one", 0] IE JavaScript Guru Challenge: figure out each engine’s underlying implementation of sort() by looking at these results.
  8. 9 Introduction | Premise | Challengers | TypeScript Most of

    us are just baffled by it. function sortFuncAsc(a,b) { return a-b; } var points = [40,100,1,5,25,10]; points.sort(sortFuncAsc); // [1, 5, 10, 25, 40, 100] var points = ["apple", "banana", "pear", "zebra", "peach", "35", "", 53]; points.sort(sortFuncAsc); // ["pear", "banana", "zebra", "peach", "35", "", "apple", 53] Mixed type bags to be sorted is a fishy concept by itself, but why does JavaScript feel the need to keep chugging along? Why doesn’t this throw an exception? What could we possibly gain as developers by making these allowances?
  9. Crockford says in “JavaScript: The Good Parts” intro: Javascript is

    a language with more than its share of bad parts. It went from non-existence to global adoption in an alarmingly short period of time. It never had an interval in the lab when it could be tried out and polished. It went straight into Netscape Navigator 2 just as it was, and it was very rough. When Java™ applets failed, JavaScript became the “Language of the Web” by default. JavaScript’s popularity is almost completely independent of its qualities as a programming language. […] The best nature of JavaScript is so effectively hidden that for many years the prevailing opinion of JavaScript was that it was an unsightly, incompetent toy. […] There was no careful review of the language or its problem domain. There was no review of its suitability or the soundness of its design. It was slapped together at Netscape, and then copied elsewhere. Given the process that created JavaScript and made it a de facto standard, we deserve something far worse. Javascript is a language of many contrasts. It contains many errors and sharp edges, so you might wonder, “Why should I use JavaScript?” There are two answers. The first is that you don’t have a choice. 10 Introduction | Premise | Challengers | TypeScript
  10. “ ” The first is that you don’t have a

    choice. 11 Introduction | Premise | Challengers | TypeScript But maybe that’s not entirely true now...
  11. My gripes with JavaScript as a C++ developer: • Dynamic

    typing in an age of static typing (weak or strong) resurgence due to improved language expressiveness to declare interfaces, contracts, constraints and concepts. Tooling, symbol navigation, static analysis and profiling are fields heavily tied to the ability to reason about types before runtime. 12 Introduction | Premise | Challengers | TypeScript
  12. My gripes with JavaScript as a C++ developer: • Dynamic

    typing in an age of static typing (weak or strong) resurgence due to improved language expressiveness to declare interfaces, contracts, constraints and concepts. Tooling, symbol navigation, static analysis and profiling are fields heavily tied to the ability to reason about types before runtime. • Every object is an associative array. Keys are always strings. Performance suffers at the expense of allowing a limited form of reflection and, most importantly, duck typing. JIT-ing may work around this, but only insofar as it can reason it won’t have any side-effects. And if you’re hinting the JITter, you may as well simply statically type. 13 Introduction | Premise | Challengers | TypeScript
  13. My gripes with JavaScript as a C++ developer: • Dynamic

    typing in an age of static typing (weak or strong) resurgence due to improved language expressiveness to declare interfaces, contracts, constraints and concepts. Tooling, symbol navigation, static analysis and profiling are fields heavily tied to the ability to reason about types before runtime. • Every object is an associative array. Keys are always strings. Performance suffers at the expense of allowing a limited form of reflection and, most importantly, duck typing. JIT-ing may work around this, but only insofar as it can reason it won’t have any side-effects. And if you’re hinting the JITter, you may as well simply statically type. • Numerics are floats. Always. Quoting the Standard: 4.3.19 Number value primitive value corresponding to a double-precision 64-bit binary format IEEE 754 value NOTE A Number value is a member of the Number type and is a direct representation of a number. 14 Introduction | Premise | Challengers | TypeScript
  14. My gripes with JavaScript as a C++ developer: • Dynamic

    typing in an age of static typing (weak or strong) resurgence due to improved language expressiveness to declare interfaces, contracts, constraints and concepts. Tooling, symbol navigation, static analysis and profiling are fields heavily tied to the ability to reason about types before runtime. • Every object is an associative array. Keys are always strings. Performance suffers at the expense of allowing a limited form of reflection and, most importantly, duck typing. JIT-ing may work around this, but only insofar as it can reason it won’t have any side-effects. And if you’re hinting the JITter, you may as well simply statically type. • Numerics are floats. Always. Quoting the Standard: 4.3.19 Number value primitive value corresponding to a double-precision 64-bit binary format IEEE 754 value NOTE A Number value is a member of the Number type and is a direct representation of a number. • While prototype-based OOP is not inherently worse than class-based, __proto__ traversal is slow where non- virtuals aren’t. The “this” pointer’s context could be just about anything, no clear guidelines apply. 15 Introduction | Premise | Challengers | TypeScript
  15. My gripes with JavaScript as a C++ developer 2 :

    Electric Boogaloo • Here’s some words you won’t find in the ECMAScript Standard: “garbage”, “destructor”, “finalizer”, “deterministic”, “cleanup”, “free” (in the allocation sense), “allocation”, “memory” (except once, when talking about RegExp pattern evaluation). Huh. 16 Introduction | Premise | Challengers | TypeScript
  16. My gripes with JavaScript as a C++ developer 2 :

    Electric Boogaloo • Here’s some words you won’t find in the ECMAScript Standard: “garbage”, “destructor”, “finalizer”, “deterministic”, “cleanup”, “free” (in the allocation sense), “allocation”, “memory” (except once, when talking about RegExp pattern evaluation). Huh. • If the word “memory” is not there, “memory model” is also a no-show. It is no surprise then that “thread” is never mentioned. Not only is ECMAScript incapable of reasoning about synchronization primitives, atomics, volatiles or memory barriers: whether the implementation is single-threaded or multi-threaded is undefined. 17 Introduction | Premise | Challengers | TypeScript
  17. My gripes with JavaScript as a C++ developer 2 :

    Electric Boogaloo • Here’s some words you won’t find in the ECMAScript Standard: “garbage”, “destructor”, “finalizer”, “deterministic”, “cleanup”, “free” (in the allocation sense), “allocation”, “memory” (except once, when talking about RegExp pattern evaluation). Huh. • If the word “memory” is not there, “memory model” is also a no-show. It is no surprise then that “thread” is never mentioned. Not only is ECMAScript incapable of reasoning about synchronization primitives, atomics, volatiles or memory barriers: whether the implementation is single-threaded or multi-threaded is undefined. • No common or Standard Library. ECMAScript implementations (JavaScript, ActionScript, Node.js, etc.) have no common ground when it comes to simple matters such as Date/Time facilities, Unicode conversions, I/O, Math and Random. CommonJS is an active project that aims to deal with this precise matter. 18 Introduction | Premise | Challengers | TypeScript
  18. My gripes with JavaScript as a C++ developer 2 :

    Electric Boogaloo • Here’s some words you won’t find in the ECMAScript Standard: “garbage”, “destructor”, “finalizer”, “deterministic”, “cleanup”, “free” (in the allocation sense), “allocation”, “memory” (except once, when talking about RegExp pattern evaluation). Huh. • If the word “memory” is not there, “memory model” is also a no-show. It is no surprise then that “thread” is never mentioned. Not only is ECMAScript incapable of reasoning about synchronization primitives, atomics, volatiles or memory barriers: whether the implementation is single-threaded or multi-threaded is undefined. • No common or Standard Library. ECMAScript implementations (JavaScript, ActionScript, Node.js, etc.) have no common ground when it comes to simple matters such as Date/Time facilities, Unicode conversions, I/O, Math and Random. CommonJS is an active project that aims to deal with this precise matter. • No “byte” primitive. No elegant way to handle transport, protocols, streams, endianness, compression, hashing, obfuscation nor cryptography. UTF-8 characters and floating point numbers make for poor replacements. 19 Introduction | Premise | Challengers | TypeScript
  19. My gripes with JavaScript as a C++ developer 3 :

    Boogaloo Harder • Implementations are largely Garbage Collected, as the language omits proper out-of-the-box constructs to handle object lifetime. While GC is a mature and proven technique, low-power devices and mobile computing greatly benefit from deterministic destruction. Coupled with the lack of concurrency guarantees, all of ECMAScript seems counter to current trends in computing. 20 Introduction | Premise | Challengers | TypeScript
  20. My gripes with JavaScript as a C++ developer 3 :

    Boogaloo Harder • Implementations are largely Garbage Collected, as the language omits proper out-of-the-box constructs to handle object lifetime. While GC is a mature and proven technique, low-power devices and mobile computing greatly benefit from deterministic destruction. Coupled with the lack of concurrency guarantees, all of ECMAScript seems counter to current trends in computing. • The DOM facility is unusable, forever wrapped over by a more competent framework such as jQuery. 21 Introduction | Premise | Challengers | TypeScript
  21. My gripes with JavaScript as a C++ developer 3 :

    Boogaloo Harder • Implementations are largely Garbage Collected, as the language omits proper out-of-the-box constructs to handle object lifetime. While GC is a mature and proven technique, low-power devices and mobile computing greatly benefit from deterministic destruction. Coupled with the lack of concurrency guarantees, all of ECMAScript seems counter to current trends in computing. • The DOM facility is unusable, forever wrapped over by a more competent framework such as jQuery. • No native support for Futures and Promises, in a language that experienced a surge in popularity precisely by allowing advanced UI manipulation in a medium that desperately needed it. 22 Introduction | Premise | Challengers | TypeScript
  22. My gripes with JavaScript as a C++ developer 3 :

    Boogaloo Harder • Implementations are largely Garbage Collected, as the language omits proper out-of-the-box constructs to handle object lifetime. While GC is a mature and proven technique, low-power devices and mobile computing greatly benefit from deterministic destruction. Coupled with the lack of concurrency guarantees, all of ECMAScript seems counter to current trends in computing. • The DOM facility is unusable, forever wrapped over by a more competent framework such as jQuery. • No native support for Futures and Promises, in a language that experienced a surge in popularity precisely by allowing advanced UI manipulation in a medium that desperately needed it. • It borrows C’s syntax -a statically typed, compiled language closer to a high-level assembler than what we understand today for a programming language- for a dynamically typed, interpreted language. Did we really need switch case fall-through? 23 Introduction | Premise | Challengers | TypeScript
  23. 24 Introduction | Premise | Challengers | TypeScript ♩ Ragtime

    music starts playing ♬ P.T.G. presents
  24. 25 Introduction | Premise | Challengers | TypeScript An Offensive

    but Briefly Accurate History of JavaScript
  25. How good a JavaScript coder are you? • Did you

    remember to “use strict”? • Do you know when to use the strict and coercing forms of the comparison operator? • Dynamic content? How do you programmatically build strings while minimizing temporaries? • Do you understand the scope hoisting rules? What’s ‘var’ for? How function names are tied to the global namespace as opposed to function objects? How about local scope of variables? What’s the ‘let’ keyword for? • Can you tell the “type” of an object? Even if it comes from a different window? Have you stopped asking for the type of objects and simply respect their duck-ness? • Do you ‘get’ prototypes? Why is __proto__ different from prototype? • Can you replicate the visibility patters for public, privileged (protected) and private without looking it up in Crockford’s homepage? • Do you understand the difference between string, Boolean and Number primitives and objects? • Do you know when to access nested variables by the member access operator and when to use the key indexer notation? What about non-string keys? • What does the ‘new’ keyword actually do? Why are there so many ways to build new objects? Must I use all? 41 Introduction | Premise | Challengers | TypeScript
  26. How good a JavaScript coder are you? (Firefox Guru version)

    • Iterators, do you even use them? What about generators? • Do you ‘get’ code using generator expressions and array comprehension? • { do you { still write unnecessary } brackets in your event handlers } or use expression closures? • Did you know your JSON2 library pretty much delegates the task to the browser as JavaScript now has native JSON support? • Do you use Object’s new facilities? Do you freeze properties to ensure immutability semantics in your functional code? Do you prevent misuse by inhibiting extension or sealing them? • Speaking of that, do you use actual properties? Getters and setters? • What about their descriptors? Do you know how to set and query these settings? • Proxies. I bet you never heard of these. Do you regularly encounter challenges where they are most welcome? • Can you more or less re-implement DOM related methods of jQuery using naught but the native window and document objects? • What about the AJAX calls? Or the promise/future utilities? What about the algorithm facilities of jQuery or Underscore.js? 42 Introduction | Premise | Challengers | TypeScript
  27. How good a JavaScript coder are you? • And the

    truly important one: are you expecting with bated breath some feature from ECMAScript Harmony that is not class? 43 Introduction | Premise | Challengers | TypeScript
  28. … how good are you at ECMAScript? 45 Introduction |

    Premise | Challengers | TypeScript
  29. Because only one browser owns JavaScript. Most of the cool

    things are just toys in Mozilla’s backyard. It’s not about IE being retarded either, almost nothing works in Chrome/Safari. Some things do but as experimental “--harmony” switches. Check http://kangax.github.io/es5-compat-table/es6/ and weep. Then check the ES5 compatibility table and slowly realize what little of the things Mozilla implemented during the ‘00s was actually formalized into the current Standard. 46 Introduction | Premise | Challengers | TypeScript
  30. …excuse me, I’m just going to put this here while

    I keep talking… 47 Introduction | Premise | Challengers | TypeScript » [1, 2, 10].sort() » [1, 10, 2]
  31. In the end, you did not need this Introduction; you

    already struggle with JavaScript and large-scale development. 48 Introduction | Premise | Challengers | TypeScript » [1, 2, 10].sort() » [1, 10, 2]
  32. You use MV* frameworks, but you still feel you’re making

    a mess inside each single [M], [V] and [*]. 49 Introduction | Premise | Challengers | TypeScript
  33. What’s more, you don’t know how to express common ground

    for all [M]s, [V]s or [*]s in a reliable fashion. 50 Introduction | Premise | Challengers | TypeScript
  34. As a matter of fact, you have a hard time

    performing high-level reasoning over “plain JavaScript objects”. 51 Introduction | Premise | Challengers | TypeScript
  35. And everything you end up writing feels like a CSS

    class, extra <div> or variable rename away from spitting undefined, [] and ReferenceError. 52 Introduction | Premise | Challengers | TypeScript
  36. In other words: redundancy, boilerplate brittleness (refactor or misuse), spaghetti-code,

    un-testability. 53 Introduction | Premise | Challengers | TypeScript
  37. You already told yourself “this time I’m going to be

    disciplined”. 54 Introduction | Premise | Challengers | TypeScript
  38. You already bought the frameworks to force discipline into your

    project. 55 Introduction | Premise | Challengers | TypeScript
  39. “ ” TypeScript wins when you look upon the flaws

    of the alternatives I n t r o d u c t i o n | Premise | C h a l l e n g e r s | T y p e S c r i p t 57
  40. No post-JavaScript language is terrible. Even Harmony and post-Harmony ECMAScript

    is looking decent. I even got the urge to try it out while researching for these slides. BTW, did you notice this in Mozilla’s MDN site: *JavaScript is a trademark or registered trademark of Oracle in the U.S. and other countries. Oracle up-Sunning Sun, gentlemen. 58 Introduction | Premise | Challengers | TypeScript
  41. I can’t make a fair comparison of all post-JS Web

    languages, feature by feature. 59 Introduction | Premise | Challengers | TypeScript
  42. “Chrestomathy”: a collection of choice literary passages, used especially as

    an aid in learning a subject. 61 Introduction | Premise | Challengers | TypeScript
  43. what who philosophy some nice features token code sample oh,

    that one thing that makes it useless 62 Introduction | Premise | Challengers | TypeScript
  44. “ ” JSX I n t r o d u

    c t i o n | P r e m i s e | Challengers | T y p e S c r i p t 65
  45. By “:DeNA”, Japanese company that specializes in mobile and social

    media gaming. Currently at 0.9.72. Provided under the MIT license. Compiles to JavaScript. Can hint for the Closure compiler. Performs more aggressive in-lining of methods. Static Typing, Class-based OOP , Interfaces, Mix-ins, Generators, Templates, Imports (Python/Node.js like) 66 Introduction | Premise | Challengers | TypeScript
  46. 67 Introduction | Premise | Challengers | TypeScript A JSX

    code sample. /*** * An example to use class templates */ class Queue.<T> { var _buf = new Array.<T>; function constructor() { } function enqueue(value : T) : void { this._buf.push(value); } function dequeue() : T { if (this.isEmpty()) { throw new Error("empty queue"); } return this._buf.shift(); } function isEmpty() : boolean { return this._buf.length == 0; } } class _Main { static function main(args : string[]) : void { var queue = new Queue.<string>; queue.enqueue("foo"); queue.enqueue("bar"); log queue.dequeue(); log queue.dequeue(); } } Un-compiled JSX source implementing a type-safe generic queue.
  47. 68 Introduction | Premise | Challengers | TypeScript // generatedy

    by JSX compiler 0.9.63 (2013-08-31 12:05:12 +0900; 2ec017d883d4d01af3d13db10eb1dfa291034b54) var JSX = {}; (function (JSX) { /** * extends the class */ function $__jsx_extend(derivations, base) { var ctor = function () {}; ctor.prototype = base.prototype; var proto = new ctor(); for (var i in derivations) { derivations[i].prototype = proto; } } /** * copies the implementations from source interface to target */ function $__jsx_merge_interface(target, source) { for (var k in source.prototype) if (source.prototype.hasOwnProperty(k)) target.prototype[k] = source.prototype[k]; } /** * defers the initialization of the property */ function $__jsx_lazy_init(obj, prop, func) { function reset(obj, prop, value) { delete obj[prop]; obj[prop] = value; return value; } Object.defineProperty(obj, prop, { get: function () { return reset(obj, prop, func()); }, set: function (v) { reset(obj, prop, v); }, enumerable: true, configurable: true }); } /** * sideeffect().a /= b */ function $__jsx_div_assign(obj, prop, divisor) { return obj[prop] = (obj[prop] / divisor) | 0; } /* * global functions, renamed to avoid conflict with local variable names */ var $__jsx_parseInt = parseInt; var $__jsx_parseFloat = parseFloat; function $__jsx_isNaN(n) { return n !== n; } var $__jsx_isFinite = isFinite; var $__jsx_encodeURIComponent = encodeURIComponent; var $__jsx_decodeURIComponent = decodeURIComponent; var $__jsx_encodeURI = encodeURI; var $__jsx_decodeURI = decodeURI; var $__jsx_ObjectToString = Object.prototype.toString; var $__jsx_ObjectHasOwnProperty = Object.prototype.hasOwnProperty; /* * profiler object, initialized afterwards */ function $__jsx_profiler() { } /* * public interface to JSX code */ JSX.require = function (path) { var m = $__jsx_classMap[path]; return m !== undefined ? m : null; }; JSX.profilerIsRunning = function () { return $__jsx_profiler.getResults != null; }; JSX.getProfileResults = function () { return ($__jsx_profiler.getResults || function () { return {}; })(); }; JSX.postProfileResults = function (url, cb) { if ($__jsx_profiler.postResults == null) throw new Error("profiler has not been turned on"); return $__jsx_profiler.postResults(url, cb); }; JSX.resetProfileResults = function () { if ($__jsx_profiler.resetResults == null) throw new Error("profiler has not been turned on"); return $__jsx_profiler.resetResults(); }; JSX.DEBUG = true; function StopIteration() { Error.call(this); this.name = "StopIteration"; if (Error.captureStackTrace) Error.captureStackTrace(this, StopIteration); }; $__jsx_extend([StopIteration], Error); function _Main() { }; $__jsx_extend([_Main], Object); function _Main$main$AS(args) { var queue; queue = new Queue$x2E$x3Cstring$x3E(); queue.enqueue$S("foo"); queue.enqueue$S("bar"); console.log(queue.dequeue$()); console.log(queue.dequeue$()); }; _Main.main = _Main$main$AS; _Main.main$AS = _Main$main$AS; function Queue$x2E$x3Cstring$x3E() { this._buf = []; }; $__jsx_extend([Queue$x2E$x3Cstring$x3E], Object); Queue$x2E$x3Cstring$x3E.prototype.enqueue$S = function (value) { this._buf.push(value); }; Queue$x2E$x3Cstring$x3E.prototype.dequeue$ = function () { if (this.isEmpty$()) { throw new Error("empty queue"); } return (function (v) { if (! (v != null)) { debugger; throw new Error("[source- map/template.jsx:18:26] null access\n return this._buf.shift();\n ^\n"); } return v; }(this._buf.shift())); }; Queue$x2E$x3Cstring$x3E.prototype.isEmpty$ = function () { return this._buf.length === 0; }; var $__jsx_classMap = { "system:lib/built-in.jsx": { StopIteration: StopIteration, StopIteration$: StopIteration }, "source-map/template.jsx": { _Main: _Main, _Main$: _Main } }; })(JSX); JSX.require('source- map/template.jsx')._Main.main$AS([]); Compiled JSX, valid JavaScript with boilerplate class code, name mangling and loading of “template” boilerplate code into scope.
  48. Low level of awareness, active discussion, penetration and library support.

    Not being worked on by a member of the ECMAScript committee. 69 Introduction | Premise | Challengers | TypeScript
  49. “ ” Closure I n t r o d u

    c t i o n | P r e m i s e | Challengers | T y p e S c r i p t 70
  50. By Google, active and important member of the ECMAScript committee.

    Currently at v20140110. Provided under the Apache license 2.0. Compiles JavaScript into better JavaScript machine-wise. Leverages specific hint annotations interspersed in the code as traditional comments. Provides warnings against “unsafe” or problematic usages of JS. Being JavaScript, roughly same feature set as ECMAScript 3. Upping the level of optimizations applied progressively restrict some corner cases. 71 Introduction | Premise | Challengers | TypeScript
  51. 72 Introduction | Premise | Challengers | TypeScript A Closure

    code sample. // ==ClosureCompiler== // @output_file_name default.js // @compilation_level ADVANCED_OPTIMIZATIONS // ==/ClosureCompiler== // ------------------ // functional version // ------------------ (function (n) { var r = []; while (n--) { r.push(n + 1); } return r.reverse(); })(100).map(function (n) { return !(n % 15) ? 'FizzBuzz' : !(n % 3) ? 'Fizz' : !(n % 5) ? 'Buzz' : n; }).join('\r\n'); Un-compiled JS source implementing FizzBuzz the functional way.
  52. 73 Introduction | Premise | Challengers | TypeScript for(var b=100,c=[];b--;)c.push(b+1);c.reverse().map(function(a){return

    a%15?a%3?a%5?a:"Buzz":"Fizz":"FizzBuzz"}); Compiled version, using ‘advanced’ compilation. Minification aside, note the rewrite deduced by control flow analysis, constant folding and tail call optimization.
  53. It’s same old JavaScript, now harder to read and debug.

    Hinting is cumbersome if done manually. 74 Introduction | Premise | Challengers | TypeScript
  54. “ ” GWT I n t r o d u

    c t i o n | P r e m i s e | Challengers | T y p e S c r i p t 75
  55. By Google, active and important member of the ECMAScript committee.

    Currently at 2.5.1. Provided under the Apache license 2.0. ‘Google Web Toolkit’ or ‘gwit’. Trans-compiles Java to JavaScript. Comes with JS implementations of commonly used Java classes from the library packages. (such as java.lang, java.util) Being Java, it features static typing, class-based OOP , generic programming through type erasure, checked exceptions, interfaces, automatic memory management, etc. 76 Introduction | Premise | Challengers | TypeScript
  56. Too far removed from the “Web”, generally hard to communicate

    with things built outside this ecosystem. If you have issues with Java, you have them with GWT. 77 Introduction | Premise | Challengers | TypeScript
  57. “ ” HAXE I n t r o d u

    c t i o n | P r e m i s e | Challengers | T y p e S c r i p t 78
  58. Developed by the HAXE Foundation. Currently at 3.0.1. Provided under

    the GPL v2 license (library: MIT) A successor to ActionScript 2.0 (also an ECMAScript implementation). Can compile bytecode for different virtual machines, such as Flash, and trans-compile to other targets such as AS3 or JavaScript. Statically typed, class-based OOP , interfaces, functors, anonymous types, and a form of generic programming based on type erasure and constraints. 79 Introduction | Premise | Challengers | TypeScript
  59. 80 Introduction | Premise | Challengers | TypeScript A HAXE

    code sample. public static function memoize(func:Dynamic , hash_size:Int = 100) : Dynamic { var arg_hash = new Hash<Dynamic>(); var f = function(args:Array<Dynamic>){ var arg_string = args.join('|'); if (arg_hash.exists(arg_string)) return arg_hash.get(arg_string); else{ var ret = Reflect.callMethod({},func,args); if(Lambda.count(arg_hash) < hash_size) arg_hash.set(arg_string, ret); return ret; } } f = Reflect.makeVarArgs(f); return f; } A memoizer, a function that caches the result in case it’s called with the same argument(s).
  60. Don’t even want to know what that ends up looking

    like in JS. 81 Introduction | Premise | Challengers | TypeScript
  61. “ ” LLJS I n t r o d u

    c t i o n | P r e m i s e | Challengers | T y p e S c r i p t 83
  62. By Mozilla, active and important member of the ECMAScript committee.

    Provided under the MIT license. Compiles to a subset of JavaScript that is highly optimizable by AOT (ahead of time) compilers. Meant for performance-critical blocks of code. Static Typing, block scoped, limited to primitives and an “any” type for inter-op, structs, unions, pointers, heap and stack arrays, manual memory management, implements “memory” by using JavaScript’s Typed Arrays singletons (works in all major browsers). Member scoping results in addressable offsets, no indirection, no GC activity/pressure. 84 Introduction | Premise | Challengers | TypeScript
  63. 85 Introduction | Premise | Challengers | TypeScript A LLJS

    code sample. struct Node { Node *next; int value; }; let Node *head = new Node, *tail = head; function Node *add(int value) { let Node *next = new Node; next->value = value; tail->next = next; tail = next; return next; } trace(add(1)); trace(add(2)); trace(add(3)); traceList(head->next); function void traceList(Node *p) { while (p) { trace("Node at address: " + p + ", has value: " + p- >value); p = p->next; } } A space efficient linked list using pointers and a struct, noticeably smaller than instancing objects. Far easier to reclaim its memory than for a GC to evaluate inter-dependencies. Faster to access nodes with less indirection, potentially allocated in a more contiguous sense RAM-wise.
  64. 86 Introduction | Premise | Challengers | TypeScript const $M

    = require('memory'); $M.set_memcheck(false); const $malloc = $M.malloc, $U4 = $M.U4; var head = $malloc(8) >> 2, tail = head; function add(value) { const $malloc = $M.malloc, $I4 = $M.I4, $U4 = $M.U4; var next = $malloc(8) >> 2; $I4[next + 1] = value; $U4[tail] = next; tail = next; return next; } trace(add(1)); trace(add(2)); trace(add(3)); traceList($U4[head]); function traceList(p) { const $I4 = $M.I4, $U4 = $M.U4; while (p) { trace('Node at address: ' + p + ', has value: ' + $I4[p + 1]); p = $U4[p]; } } Compiled LLJS, notice the array singletons for each primitive type.
  65. Useful for highly performing or timing-critical code, as it introduces

    no GC pauses of its own. Unviable for large-scale application development. Could be leveraged as an intermediate language. 87 Introduction | Premise | Challengers | TypeScript
  66. “ ” asm.js I n t r o d u

    c t i o n | P r e m i s e | Challengers | T y p e S c r i p t 88
  67. By Mozilla, active and important member of the ECMAScript committee.

    Provided under the MIT license. A very strict subset of JavaScript that is highly optimizable by AOT (ahead of time) compilers. All major browsers currently detect asm.js code and optimize accordingly. Did not start truly as a language, nor a compilation target language, but the formalization of a pattern that allows aggressive optimization strategies, independently discovered by Emscripten and Mandreel. Other languages we will discuss here target asm.js rather than JavaScript proper, or at least are considering the possibility. 89 Introduction | Premise | Challengers | TypeScript
  68. 90 Introduction | Premise | Challengers | TypeScript An asm.js

    code sample. function Vb(d) { d = d | 0; var e = 0, f = 0, h = 0, j = 0, k = 0, l = 0, m = 0, n = 0, o = 0, p = 0, q = 0, r = 0, s = 0; e = i; i = i + 12 | 0; f = e | 0; h = d + 12 | 0; j = c[h >> 2] | 0; if ((j | 0) > 0) { c[h >> 2] = 0; k = 0 } else { k = j } j = d + 24 | 0; if ((c[j >> 2] | 0) > 0) { c[j >> 2] = 0 } l = d + 28 | 0; c[l >> 2] = 0; c[l + 4 >> 2] = 0; l = (c[1384465] | 0) + 3 | 0; do { if (l >>> 0 < 26) { if ((4980736 >>> (l >>> 0) & 1 | 0) == 0) { break } if ((c[1356579] | 0) > 0) { m = d + 4 | 0; n = 0; while (1) { o = c[(c[1356577] | 0) + (n << 2) >> 2] | 0; do { if (a[o + 22 | 0] << 24 >> 24 == 24) { if (!(Vp(d, o | 0) | 0)) { break } p = (c[m >> 2] | 0) + (((c[h >> 2] | 0) - 1 | 0) * 40 & -1) + 12 | 0; q = o + 28 | 0; c[p >> 2] = c[q >> 2] | 0; c[p + 4 >> 2] = c[q + 4 >> 2] | 0; c[p + 8 >> 2] = c[q + 8 >> 2] | 0; c[p + 12 >> 2] = c[q + 12 >> 2] | 0; c[p + 16 >> 2] = c[q + 16 >> 2] | 0; c[p + 20 >> 2] = c[q + 20 >> 2] | 0; c[p + 24 >> 2] = c[q + 24 >> 2] | 0 } } while (0); o = n + 1 | 0; if ((o | 0) < (c[1356579] | 0)) { n = o } else { break } } r = c[h >> 2] | 0 } else { r = k } if ((r | 0) == 0) { i = e; return } n = c[j >> 2] | 0; if ((n | 0) >= 1) { i = e; return } m = f | 0; o = f + 4 | 0; q = f + 8 | 0; p = n; while (1) { g[m >> 2] = 0.0; g[o >> 2] = 0.0; g[q >> 2] = 0.0; Vq(d, p, f, 0, -1e3); n = c[j >> 2] | 0; if ((n | 0) < 1) { p = n A method from the BananaBread demo, a 3D first person shooter using WebGL. Don’t bother trying to read this.
  69. If you use this for development you are throwing fifty

    years of computer science away. Is meant as an intermediate language. The Right Answer for the “JavaScript alternative” question may depend in the future on how asm.js is leveraged, if we still compile to JS. 91 Introduction | Premise | Challengers | TypeScript
  70. “ ” Emscripten I n t r o d u

    c t i o n | P r e m i s e | Challengers | T y p e S c r i p t 92
  71. Project founded by Alon Zakai of Mozilla, leveraging the LLVM

    community. Provided under the MIT license. An LLVM trans-compiler that targets asm.js. Any language that compiles to LLVM can be used to write complex JavaScript applications. Primary languages fostered at LLVM are C, C++ and Objective-C. 93 Introduction | Premise | Challengers | TypeScript
  72. Since we’re not working on the Unreal 3 engine, but

    mostly need to perform DOM updates and AJAX calls, our code would be a terrible mess of emscripten_run_script() evaluating pieces of JS everywhere. Much in the same way we could code C++ and target the .NET framework with C++/CX, it’s a good option to deal with space- & time-expensive code that needs to run on the client side rather than the server. 94 Introduction | Premise | Challengers | TypeScript
  73. “ ” NaCL I n t r o d u

    c t i o n | P r e m i s e | Challengers | T y p e S c r i p t 95
  74. By Google, active and important member of the ECMAScript committee.

    Currently at version 32.0. Provided under the new BSD license. A clever way to run a “safe” subset of x86 and ARM instructions in a sandbox, as a mechanism to safely run native code from within a web browser. A companion project, PNaCL (P for Portable), allows architecture-independent deployment, allowing each client to pre-compile to suit their needs. (not unlike MSIL on mono/.NET) Supports C/C++, excluding parts of the Standard Library that deal with things outside the sandbox. 96 Introduction | Premise | Challengers | TypeScript
  75. We already tried something like this before, it was called

    ActiveX and it never worked outside of IE (if it worked at all). Mozilla’s Jay Sullivan says: "These native apps are just little black boxes in a webpage. [...] We really believe in HTML, and this is where we want to focus.“ Forget about widespread browser adoption. 97 Introduction | Premise | Challengers | TypeScript
  76. “ ” Dart I n t r o d u

    c t i o n | P r e m i s e | Challengers | T y p e S c r i p t 99
  77. By Google, active and important member of the ECMAScript committee.

    Currently at version 1.0.0.10. Provided under the new BSD license. Dart programs can be run in the Dart VM, or trans-compiled to JavaScript. During August 2013 Google reports performance of the generated JS is within 78% of hand-written JS. Optionally typed, class-based OOP , single inheritance, abstract classes, interfaces, reified generics. 100 Introduction | Premise | Challengers | TypeScript
  78. 101 Introduction | Premise | Challengers | TypeScript A Dart

    code sample. int rand(int max) => (Math.random()*max).toInt(); class Game { int _prize; int _open; int _chosen; Game() { _prize=rand(3); _open=null; _chosen=null; } void choose(int door) { _chosen=door; } void reveal() { if(_prize==_chosen) { int toopen=rand(2); if (toopen>=_prize) toopen++; _open=toopen; } else { for(int i=0;i<3;i++) if(_prize!=i && _chosen!=i) { _open=i; break; } } } void change() { for(int i=0;i<3;i++) if(_chosen!=i && _open!=i) { _chosen=i; break; } } bool hasWon() => _prize==_chosen; String toString() { String res="Prize is behind door $_prize"; if(_chosen!=null) res+=", player has chosen door $_chosen"; if(_open!=null) res+=", door $_open is open"; return res; } } void play(int count, bool swap) { int wins=0; for(int i=0;i<count;i++) { Game game=new Game(); game.choose(rand(3)); game.reveal(); if(swap) game.change(); if(game.hasWon()) wins++; } String withWithout=swap?"with":"without"; double percent=(wins*100.0)/count; print("playing $withWithout switching won $percent%"); } test() { for(int i=0;i<5;i++) { Game g=new Game(); g.choose(i%3); g.reveal(); print(g); g.change(); print(g); print("win==${g.hasWon()}"); } } main() { play(10000,false); play(10000,true); } The Monty Hall Problem; don’t all languages start looking the same at this point?
  79. Brendan Eich, creator of JavaScript and now Mozilla’s CTO stated:

    “I guarantee you that Apple and Microsoft (and Opera and Mozilla, but the first two are enough) will never embed the Dart VM.” Microsoft and Apple have stated similar remarks, denoting on the harmfulness of adding a new web facing language. 102 Introduction | Premise | Challengers | TypeScript
  80. “ ” CoffeeScript I n t r o d u

    c t i o n | P r e m i s e | Challengers | T y p e S c r i p t 105 Jeremy Ashkenas*
  81. Created by Jeremy Ashkenas, of Backbone.js and Underscore.js fame. Yeah,

    that Jeremy. Currently at version 1.6.3. Provided under the MIT license. Trans-compiles to JavaScript one-to-one; no extra interpretation required at runtime. Ruby/Haskell-like, popular enough to be built-in into Ruby on Rails, ranks low in the TIOBE index (#170) but ranks high in GitHub / StackOverflow. Can generate ‘source maps’ to map JS statements with their CS counterpart, aiding in debugging. 106 Introduction | Premise | Challengers | TypeScript
  82. Dynamically typed, lambda expressions, indentation affects initialization and scope, control

    statements have return types, rest parameters, list comprehension, slices, nil operator, single-inheritance classes, destructuring assignment, explicit binding of “this”, chained comparisons, string interpolation. 107 Introduction | Premise | Challengers | TypeScript
  83. 108 Introduction | Premise | Challengers | TypeScript A CoffeeScript

    code sample. class Animal constructor: (@name) -> move: (meters) -> alert @name + " moved #{meters}m." class Snake extends Animal move: -> alert "Slithering..." super 5 class Horse extends Animal move: -> alert "Galloping..." super 45 sam = new Snake "Sammy the Python" tom = new Horse "Tommy the Palomino" sam.move() tom.move() The classical, terrible OOP example that makes every aspiring programmer prefer is-a relationships over has-a and uses-a.
  84. 109 Introduction | Premise | Challengers | TypeScript var Animal,

    Horse, Snake, sam, tom, _ref, _ref1, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; Animal = (function() { function Animal(name) { this.name = name; } Animal.prototype.move = function(meters) { return alert(this.name + (" moved " + meters + "m.")); }; return Animal; })(); Snake = (function(_super) { __extends(Snake, _super); function Snake() { _ref = Snake.__super__.constructor.apply(this, arguments); return _ref; } Snake.prototype.move = function() { alert("Slithering..."); return Snake.__super__.move.call(this, 5); }; return Snake; })(Animal); Horse = (function(_super) { __extends(Horse, _super); function Horse() { _ref1 = Horse.__super__.constructor.apply(this, arguments); return _ref1; } Horse.prototype.move = function() { alert("Galloping..."); return Horse.__super__.move.call(this, 45); }; return Horse; })(Animal); sam = new Snake("Sammy the Python"); tom = new Horse("Tommy the Palomino"); sam.move(); tom.move(); Trans-compiled to JavaScript, exhibiting minimal boilerplate to assist inheritance.
  85. All in all, CoffeeScript is a worthy opponent. DropBox has

    migrated all JS logic to CS; GitHub is asking its developers to write all new JS as CS. If you have a problem with significant whitespace, you’re going to have a problem with well-written CS. If you like type safety, at least compile time checking, you’re out of luck. But wait, there’s another contender… 110 Introduction | Premise | Challengers | TypeScript
  86. “ ” Harmony I n t r o d u

    c t i o n | P r e m i s e | Challengers | T y p e S c r i p t 112 Adobe, AMD, Apple, eBay, Facebook, Google, HP , IBM, Intel, Microsoft, etc.
  87. Next version (6) of the ECMAScript language. Would-be equivalent in

    Mozilla’s “JavaScript” implementation would be version 2.0. Fixes a surprising amount of gaps in the current version of the Standard when extrapolating current trends in web development. Language improvements: ‘let’ and ‘const’ keywords, destructuring assignment, for…of, iterators, generators, rest and default parameters, spread operator, arrow functions, binary/octal literals. Library improvements: map, set, WeakMap, Proxy, new number, string and Math methods, 113 Introduction | Premise | Challengers | TypeScript
  88. When I first began researching for these slides, the committee

    aimed for a December 2013 ratification of the Standard. That very same page now says December 2014. Some controversy and open discussions remain on non-trivial features. Which brings us to: 114 Introduction | Premise | Challengers | TypeScript
  89. “ ” TypeScript I n t r o d u

    c t i o n | P r e m i s e | C h a l l e n g e r s | TypeScript 115
  90. "CoffeeScript is to Ruby as TypeScript is to Java/C#/C++.“ Luke

    Hoban (co-creator of TypeScript) 116 Introduction | Premise | Challengers | TypeScript
  91. Created by Microsoft, open-source, released under the Apache License v2.0

    117 Introduction | Premise | Challengers | TypeScript
  92. Anders Hejlsberg, lead architect of C# has an active role

    on its development. 118 Introduction | Premise | Challengers | TypeScript
  93. Is a strict super-set of JavaScript. Trans-compiles to JS targeting

    either ES3 or ES5 (so far). 119 Introduction | Premise | Challengers | TypeScript
  94. Any feature with an equivalent in Harmony is aligned to

    match exactly in TS. 120 Introduction | Premise | Challengers | TypeScript
  95. Any feature diverging due to the standardization process will be

    aligned to match exactly in TS. 121 Introduction | Premise | Challengers | TypeScript
  96. As browsers implement Harmony/ES6 features, TypeScript can leverage them, code-

    and compilation-wise. 122 Introduction | Premise | Challengers | TypeScript
  97. What’s more, migrating JS to TS is painless: everything you

    wrote is already valid TS. 123 Introduction | Premise | Challengers | TypeScript
  98. Features: • Statically typed, with automatic type inference when there

    are no conflicts or ambiguities. (e.g. allowing one to write functions without specifying the signatures of its return type). This is natural to JS programmers. 124 Introduction | Premise | Challengers | TypeScript
  99. Features: • ‘Any’ type as an escape hatch from the

    typing system, much like ‘object’ in C#. Like in C#, it actually is a type that can be reasoned about. 125 Introduction | Premise | Challengers | TypeScript
  100. Features: • ‘Any’ type as an escape hatch from the

    typing system, much like ‘object’ in C#. Like in C#, it actually is a type that can be reasoned about. • Ambient declarations allow one to declare variables in scope that TypeScript currently can’t see, such as the DOM’s “document”. 126 Introduction | Premise | Challengers | TypeScript
  101. Features: • ‘Any’ type as an escape hatch from the

    typing system, much like ‘object’ in C#. Like in C#, it actually is a type that can be reasoned about. • Ambient declarations allow one to declare variables in scope that TypeScript currently can’t see, such as the DOM’s “document”. • Functions are first class citizens and can also be typed, allowing for precise callback, delegate and command processor semantics: 127 Introduction | Premise | Challengers | TypeScript function vote(candidate: string, callback: (result: string) => any) { … } var MakePoint: () => { x: number; y: number; };
  102. Features: • These typing requirements can be encapsulated as an

    interface: 128 Introduction | Premise | Challengers | TypeScript interface Friend { name: string; favoriteColor?: string; } function add(friend: Friend) { var name = friend.name; } add({ name: "Fred" }); // Ok add({ favoriteColor: "blue" }); // Error, name required add({ name: "Jill", favoriteColor: "green" }); // Ok
  103. Features: • These typing requirements can be encapsulated as an

    interface: • Interfaces can also define methods and ‘bare’ function signatures, meaning themselves are callable by passing none or more parameters that match the signature. 129 Introduction | Premise | Challengers | TypeScript interface Friend { name: string; favoriteColor?: string; } function add(friend: Friend) { var name = friend.name; } add({ name: "Fred" }); // Ok add({ favoriteColor: "blue" }); // Error, name required add({ name: "Jill", favoriteColor: "green" }); // Ok interface JQuery { text(content: string); } interface JQueryStatic { get(url: string, callback: (data: string) => any); (query: string): JQuery; }
  104. Features: • Structural subtyping, even if a class doesn’t explicitly

    implement an interface but it matches all contract requirements, it is considered valid input for methods expecting the interface type. Duck-typing mixed with static typing. 130 Introduction | Premise | Challengers | TypeScript interface Point { x: number; y: number; } function getX(p: Point) { return p.x; } class CPoint { x: number; y: number; constructor(x: number, y: number) { this.x = x; this.y = y; } } getX(new CPoint(0, 0)); // Ok, fields match getX({ x: 0, y: 0, color: "red" }); // Extra fields Ok getX({ x: 0 }); // Error: supplied parameter does not match
  105. Features: • Classes are aligned with the ES6 proposal for

    the ‘class’ keyword. 131 Introduction | Premise | Challengers | TypeScript
  106. Features: • Classes are aligned with the ES6 proposal for

    the ‘class’ keyword. • Public and private visibility; used by TypeScript during its compile phase, not strictly enforced by the translated JS. 132 Introduction | Premise | Challengers | TypeScript
  107. Features: • Classes are aligned with the ES6 proposal for

    the ‘class’ keyword. • Public and private visibility; used by TypeScript during its compile phase, not strictly enforced by the translated JS. • Constructors can declare fields inline, for a more concise syntax: (BTW, expect this feature in C# soon) 133 Introduction | Premise | Challengers | TypeScript class BankAccount { constructor(public balance: number) { } deposit(credit: number) { this.balance += credit; return this.balance; } }
  108. Features: • Enums. Nothing out of the ordinary. • Specialized

    overloads for string literals can be declared; similar to a form of meta-programming with constant values common in C++: A run-time checked version is also possible, as the last example suggests. 135 Introduction | Premise | Challengers | TypeScript interface Document { createElement(tagName: "div"): HTMLDivElement; createElement(tagName: "span"): HTMLSpanElement; createElement(tagName: "canvas"): HTMLCanvasElement; createElement(tagName: string): HTMLElement; }
  109. Features: • Generic types and functions, no surprises in the

    grammar: As expected, the compiler can often deduce the generic types due to co- or contra-variance (depending on context). 136 Introduction | Premise | Challengers | TypeScript interface Array<T> { reverse(): T[]; sort(compareFn?: (a: T, b: T) => number): T[]; }
  110. Features: • Generic types and functions, no surprises in the

    grammar: As expected, the compiler can often deduce the generic types due to co- or contra-variance (depending on context). • Support for Modules, allowing code reuse, library organization and hiding implementation details. 137 Introduction | Premise | Challengers | TypeScript interface Array<T> { reverse(): T[]; sort(compareFn?: (a: T, b: T) => number): T[]; }
  111. Features: • Generic arguments can use the “extends” constraint to

    denote base-is relationships: 138 Introduction | Premise | Challengers | TypeScript interface G<T extends U, U extends Array<V>, V extends Function> { }
  112. Features: • Generic arguments can use the “extends” constraint to

    denote base-is relationships: • extends also works for interfaces/classes: 139 Introduction | Premise | Challengers | TypeScript interface G<T extends U, U extends Array<V>, V extends Function> { } interface A { a: string; } interface B extends A { b: string; } interface C extends B { c: string; }
  113. Features: • Generic arguments can use the “extends” constraint to

    denote base-is relationships: • extends also works for interfaces/classes: • Compile-time typeof(), has no impact in run-time, allows to check for structural subtyping (according to the spec, a named type and “something that looks like it” are indistinguishable). 140 Introduction | Premise | Challengers | TypeScript interface G<T extends U, U extends Array<V>, V extends Function> { } interface A { a: string; } interface B extends A { b: string; } interface C extends B { c: string; }
  114. Features: • “super” keyword is the equivalent of “base” in

    C#. 141 Introduction | Premise | Challengers | TypeScript
  115. Features: • “super” keyword is the equivalent of “base” in

    C#. • Lambda notation using => is similar to C# and aligned with ES6. 142 Introduction | Premise | Challengers | TypeScript
  116. Features: • “super” keyword is the equivalent of “base” in

    C#. • Lambda notation using => is similar to C# and aligned with ES6. • A sensible table of type requirements for logical, arithmetic, binary and conditional operators. 143 Introduction | Premise | Challengers | TypeScript
  117. Features: • “super” keyword is the equivalent of “base” in

    C#. • Lambda notation using => is similar to C# and aligned with ES6. • A sensible table of type requirements for logical, arithmetic, binary and conditional operators. • Interface implementation is a run-time check of contract matching. 144 Introduction | Premise | Challengers | TypeScript
  118. Features: • While duck-typing for interfaces is valid, classes can

    explicitly implement an interface using the “implements” keyword, gaining compile-time checks. 145 Introduction | Premise | Challengers | TypeScript
  119. Features: • While duck-typing for interfaces is valid, classes can

    explicitly implement an interface using the “implements” keyword, gaining compile-time checks. • “static” supplies non-instance properties for classes. 146 Introduction | Premise | Challengers | TypeScript
  120. Features: • While duck-typing for interfaces is valid, classes can

    explicitly implement an interface using the “implements” keyword, gaining compile-time checks. • “static” supplies non-instance properties for classes. • Can auto-initialize properties directly in the declaration. 147 Introduction | Premise | Challengers | TypeScript
  121. Features: • While duck-typing for interfaces is valid, classes can

    explicitly implement an interface using the “implements” keyword, gaining compile-time checks. • “static” supplies non-instance properties for classes. • Can auto-initialize properties directly in the declaration. • Can override members, and use “super” to access the hidden token. 148 Introduction | Premise | Challengers | TypeScript
  122. Library Support: 149 Introduction | Premise | Challengers | TypeScript

    DefinitelyTyped @ https://github.com/borisyankov/DefinitelyTyped A large repository of modules with interfaces and ambient declarations explaining all the famous libraries you depend on, allowing compile-time checking on how your code uses them. They’re even documented.
  123. Library Support: 150 Introduction | Premise | Challengers | TypeScript

    Some picks from the long list: AngularJS, Backbone.JS, Bootstrap, CouchDB, Ember.JS, fullCalendar, globalize, Grunt, handlebars, jasmine, jQuery, jwPlayer, Knockout.JS, Marionette, MongoDB, Mustache, Node.JS, PhoneGap, Raphael, Raven.JS, RethinkDB, select2, signalR, Underscore.JS
  124. Translation to JavaScript is not guaranteed to be bug-free at

    this point. But many complex projects, including TypeScript itself, already compile fine. 152 Introduction | Premise | Challengers | TypeScript
  125. Because it’s still <1.0, backwards compatibility does not apply. Newer

    releases may ship with breaking changes. 153 Introduction | Premise | Challengers | TypeScript
  126. 0.9.5 to 1.0 won’t allow generic constraints to reference themselves.

    (CRTP) function f<T extends Service<T>>(x: T) { } 154 Introduction | Premise | Challengers | TypeScript
  127. Interfaces now merge with later interfaces having a higher priority.

    155 Introduction | Premise | Challengers | TypeScript
  128. From 0.9.1 to 0.9.5, several efforts were made to stop

    the ‘any’ type from interfering with some of the language’s features. Overload resolution rules changed slightly. Lambdas immediately called on now require enclosing parentheses. etc. 156 Introduction | Premise | Challengers | TypeScript
  129. What to expect beyond 1.0: • async/await. • Mixins. (interfaces

    providing declaration and definition) 158 Introduction | Premise | Challengers | TypeScript
  130. What to expect beyond 1.0: • async/await. • Mixins. (interfaces

    providing declaration and definition) • ‘protected’ access qualifier. 159 Introduction | Premise | Challengers | TypeScript
  131. What to expect beyond 1.0: • async/await. • Mixins. (interfaces

    providing declaration and definition) • ‘protected’ access qualifier. • ES6-compatible features, modules syntax, code generation. 160 Introduction | Premise | Challengers | TypeScript
  132. What to expect beyond 1.0: • async/await. • Mixins. (interfaces

    providing declaration and definition) • ‘protected’ access qualifier. • ES6-compatible features, modules syntax, code generation. • Maybe target to asm.js? Currently an open debate at the language’s site. 161 Introduction | Premise | Challengers | TypeScript
  133. Additional notes: • A plugin for Visual Studio 2012 (VS2013

    includes native support), facilitating compile-on-build, Intellisense, warning/error parsing, etc. • R# 8.1 (a free minor update to 8) includes TypeScript support for typing assistance, code completion and code rearrangement. • The TypeScript compiler (“tsc”) is a Node.JS application installed via the ‘npm’ packet manager. • The NuGet package Bundle Transformer at CodePlex provides enhanced MVC-like bundling of resources (compilation/translation, minification, concatenation) for JS, TS, CSS, LESS, SASS, etc. • Someone forked TS to target Google’s Closure Compiler, taking leverage of all the reasoning and inference performed by the TS compiler to annotate the target JS. 162 Introduction | Premise | Challengers | TypeScript