[
  {
    "path": ".gitattributes",
    "content": "# core.autocrlf\n* text=auto\n\n*.js linguist-language=TypeScript\n"
  },
  {
    "path": ".github/workflows/build.yml",
    "content": "name: build ebook\n\non:\n  push:\n    branches:\n      - master\n  pull_request:\n    branches:\n      - master\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n    env:\n      SHA: ${{ github.sha }}\n    steps:\n      - uses: actions/checkout@v1\n      - uses: actions/setup-node@v1\n        with:\n          node-version: '12.18.2'\n      - run: sudo apt update\n      - run: sudo apt install libegl1 libopengl0 libxcb-cursor-dev\n      - run: sudo -v && wget -nv -O- https://download.calibre-ebook.com/linux-installer.sh | sudo sh /dev/stdin\n      - run: sudo npm install -g gitbook-cli\n      - run: gitbook install\n      - run: mkdir output\n      - run: gitbook pdf . ./output/typescript-book-${SHA}.pdf\n      - run: gitbook epub . ./output/typescript-book-${SHA}.epub\n      - run: gitbook mobi . ./output/typescript-book-${SHA}.mobi\n      - name: upload pdf artifact\n        uses: actions/upload-artifact@v1\n        with:\n          name: typescript-book.pdf\n          path: output/typescript-book-${{ env.SHA }}.pdf\n      - name: upload epub artifact\n        uses: actions/upload-artifact@v1\n        with:\n          name: typescript-book.epub\n          path: output/typescript-book-${{ env.SHA }}.epub\n      - name: upload mobi artifact\n        uses: actions/upload-artifact@v1\n        with:\n          name: typescript-book.mobi\n          path: output/typescript-book-${{ env.SHA }}.mobi\n"
  },
  {
    "path": ".gitignore",
    "content": "# Mac \n*.DS_Store\n\n# IDEs\n.alm\n.vscode\n\n\n# Node rules:\n## Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)\n.grunt\n\n## Dependency directory\n## Commenting this out is preferred by some people, see\n## https://docs.npmjs.com/misc/faq#should-i-check-my-node_modules-folder-into-git\nnode_modules\n\n# Book build output\n_book\n\n# eBook build output\n*.epub\n*.mobi\n*.pdf\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing\n\nThis book is developed using [GitBook](https://github.com/GitbookIO/gitbook). Authored in Markdown files (I use [atom](http://atom.io)).\n\nHere's how to setup a Dev Environment:\n\n```\nnpm install gitbook-cli -g\ngitbook install\ngitbook serve .\n```\n> Note: serve needs port `35729` (for live reload) and `4000` for serving http://localhost:4000.\n\nAlso you can mostly just edit the `.md` files in [`/docs`](https://github.com/basarat/typescript-book/docs) using github and create a Pull Request (PR).\n\n# Code\nAll the code for the book is in the `/code` folder. Tested with `atom-typescript`.\n\n### More Gitbook Tips\n* Links best work if they are relative (e.g. `./foo.md`) to the *current* file.\n* For links in the same file (`#foo-bar` style links) best to click the heading on github to get what gitbook expects.\n\n### TypeScript Compiler Docs\nThanks to the TypeScript team for providing much of the docs: https://github.com/Microsoft/TypeScript/wiki/Architectural-Overview that are used to write the compiler story.\n"
  },
  {
    "path": "GLOSSARY.md",
    "content": "# Duck Typing\nIf it walks like a duck and quacks like a duck, it is a duck. For TypeScript if it has all the members structurally then it is okay for other things (irrespecitive of name) that accept that structure.\n\n# OE\nOperating Environment. I'd like to use the term Operating System, but that is not necessarily what I mean here. Think Browser,Node.js,WScriptHost etc.\n\n# Incremental Parsing\nRe-Parsing as the user edits the code."
  },
  {
    "path": "LICENSE.md",
    "content": "Creative Commons \n\nhttps://creativecommons.org/licenses/by/4.0/\n"
  },
  {
    "path": "README.md",
    "content": "[![YouTube Channel Subscribers](https://img.shields.io/youtube/channel/subscribers/UCGD_0i6L48hucTiiyhb5QzQ?style=social)](https://www.youtube.com/@basarat)\n\nTypeScript Deep Dive\n=======\n\nLearn Professional TypeScript. I've been looking at the issues that turn up commonly when people start using TypeScript. This is based on the lessons from [Stack Overflow](http://stackoverflow.com/tags/typescript/topusers) / [DefinitelyTyped](https://github.com/DefinitelyTyped/) and general engagement with the [TypeScript community](https://github.com/TypeStrong/). You can [follow for updates](https://twitter.com/basarat) and [don't forget to ★ on GitHub](https://github.com/basarat/typescript-book) 🌹\n\n## Reviews\n\n* Thanks for the wonderful book. Learned a lot from it. ([link](https://www.gitbook.com/book/basarat/typescript/discussions/21#comment-1468279131934))\n* Its probably the Best TypeScript book out there. Good Job ([link](https://twitter.com/thelondonjs/status/756419561570852864))\n* Love how precise and clear the examples and explanations are! ([link](https://twitter.com/joe_mighty/status/758290957280346112))\n* For the low, low price of free, you get pages of pure awesomeness. Chock full of source code examples and clear, concise explanations, TypeScript Deep Dive will help you learn TypeScript development. ([link](https://www.nativescript.org/blog/details/free-book-typescript-deep-dive))\n* Just a big thank you! **Best TypeScript 2 detailed explanation!** ([link](https://www.gitbook.com/book/basarat/typescript/discussions/38))\n* This gitbook got my project going pronto. Fluent easy read 5 stars. ([link](https://twitter.com/thebabellion/status/779888195559235584))\n* I recommend the online #typescript book by @basarat you'll love it.([link](https://twitter.com/markpieszak/status/788099306590969860))\n* I've always found this by @basarat really helpful. ([link](https://twitter.com/Brocco/status/789887640656945152))\n* We must highlight TypeScript Deep Dive, an open source book.([link](https://www.siliconrepublic.com/enterprise/typescript-programming-javascript))\n* Great online resource for learning. ([link](https://twitter.com/rdfuhr/status/790193307708076035))\n* Thank you for putting this book together, and for all your hard work within the TypeScript community. ([link](https://github.com/basarat/typescript-book/pull/183#issuecomment-257799713))\n* TypeScript Deep Dive is one of the best technical texts I've read in a while. ([link](https://twitter.com/borekb/status/794287092272599040))\n* Thanks @basarat for the TypeScript Deep Dive Book. Help me a lot with my first TypeScript project. ([link](https://twitter.com/betolinck/status/797901548562960384))\n* Thanks to @basarat for this great #typescript learning resource. ([link](https://twitter.com/markuse1501/status/799116176815230976))\n* Guyz excellent book on Typescript(@typescriptlang) by @basarat ([link](https://twitter.com/deeinlove/status/813245965507260417))\n* Leaning on the legendary @basarat's \"TypeScript Deep Dive\" book heavily at the moment ([link](https://twitter.com/sitapati/status/814379404956532737))\n* numTimesPointedPeopleToBasaratsTypeScriptBook++; ([link](https://twitter.com/brocco/status/814227741696462848))\n* A book not only for typescript, a good one for deeper JavaScript knowledge as well. [link](https://www.gitbook.com/book/basarat/typescript/discussions/59)\n* In my new job, we're using @typescriptlang, which I am new to. This is insanely helpful huge thanks, @basarat! [link](https://twitter.com/netchkin/status/855339390566096896)\n* Thank you for writing TypeScript Deep Dive. I have learned so much. [link](https://twitter.com/buctwbzs/status/857198618704355328?refsrc=email&s=11)\n* Loving @basarat's @typescriptlang online book basarat.gitbooks.io/typescript/# loaded with great recipes! [link](https://twitter.com/ericliprandi/status/857608837309677568)\n* Microsoft doc is great already, but if want to \"dig deeper\" into TypeScript I find this book of great value  [link](https://twitter.com/caludio/status/876729910550831104)\n* Thanks, this is a great book 🤓🤓 [link](https://twitter.com/jjwonmin/status/885666375548547073)\n* Deep dive to typescript is awesome in so many levels. i find it very insightful. Thanks [link](https://twitter.com/orenmizr/status/891083492787970053)\n* @basarat's intro to @typescriptlang is still one of the best going (if not THE best) [link](https://twitter.com/stevealee/status/953953255968698368)\n* \n* This is sweet! So many #typescript goodies! [link](https://twitter.com/pauliescanlon/status/989898852474998784)\n\n## Get Started\nIf you are here to read the book online [get started](https://basarat.gitbook.io/typescript/getting-started).\n\n## Translations \nBook is completely free so you can copy paste whatever you want without requiring permission. If you have a translation you want me to link here. [Send a PR](https://github.com/basarat/typescript-book/edit/master/README.md).\n* [Filipino](https://github.com/themarshann/typescript-book-fil)\n* [Italian](https://github.com/TizioFittizio/typescript-book)\n* [Chinese](https://github.com/jkchao/typescript-book-chinese)\n* [Russian](https://github.com/etroynov/typescript-book)\n* [Portuguese](https://github.com/overlineink/typescript-book)\n* [Japanese](https://github.com/yohamta/typescript-book)\n* [Spanish](https://github.com/melissarofman/typescript-book)\n* [Korean](https://github.com/radlohead/typescript-book)\n* [French](https://github.com/HachemiH/typescript-book)\n* [Polish](https://github.com/mbiesiad/typescript-book/tree/pl_PL)\n* [Thai](https://github.com/futurouz/typescript-book)\n* [Bengali](https://github.com/Acesif/typescript-book)\n* [Ukrainian](https://github.com/ArtfulBits/typescript-book)\n\n## Other Options\nYou can also download one of the Epub, Mobi, or PDF formats from the [actions tab](https://github.com/basarat/typescript-book/actions) by clicking on the latest build run. You will find the files in the artifacts section.\n\n## Special Thanks\nAll the amazing [contributors](https://github.com/basarat/typescript-book/graphs/contributors) 🌹\n\n## Share\nShare URL: https://basarat.gitbook.io/typescript/\n"
  },
  {
    "path": "SUMMARY.md",
    "content": "# Summary\n\n* [Getting Started](docs/getting-started.md)\n  * [Why TypeScript](docs/why-typescript.md)\n* [JavaScript](docs/javascript/recap.md)\n  * [Equality](docs/javascript/equality.md)\n  * [References](docs/javascript/references.md)\n  * [Null vs. Undefined](docs/javascript/null-undefined.md)\n  * [this](docs/javascript/this.md)\n  * [Closure](docs/javascript/closure.md)\n  * [Number](docs/javascript/number.md)\n  * [Truthy](docs/javascript/truthy.md)\n* [Future JavaScript Now](docs/future-javascript.md)\n  * [Classes](docs/classes.md)\n    * [Classes Emit](docs/classes-emit.md)\n  * [Arrow Functions](docs/arrow-functions.md)\n  * [Rest Parameters](docs/rest-parameters.md)\n  * [let](docs/let.md)\n  * [const](docs/const.md)\n  * [Destructuring](docs/destructuring.md)\n  * [Spread Operator](docs/spread-operator.md)\n  * [for...of](docs/for...of.md)\n  * [Iterators](docs/iterators.md)\n  * [Template Strings](docs/template-strings.md)\n  * [Promise](docs/promise.md)\n  * [Generators](docs/generators.md)\n  * [Async Await](docs/async-await.md)\n* [Project](docs/project/project.md)\n  * [Compilation Context](docs/project/compilation-context.md)\n    * [tsconfig.json](docs/project/tsconfig.md)\n    * [Which Files?](docs/project/files.md)\n  * [Declaration Spaces](docs/project/declarationspaces.md)\n  * [Modules](docs/project/modules.md)\n    * [File Module Details](docs/project/external-modules.md)\n    * [global.d.ts](docs/project/globals.md)\n  * [Namespaces](docs/project/namespaces.md)\n  * [Dynamic Import Expressions](docs/project/dynamic-import-expressions.md)\n* [Node.js QuickStart](docs/quick/nodejs.md)\n* [Browser QuickStart](docs/quick/browser.md)\n* [Library QuickStart](docs/quick/library.md)\n* [TypeScript's Type System](docs/types/type-system.md)\n  * [JS Migration Guide](docs/types/migrating.md)\n  * [@types](docs/types/@types.md)\n  * [Ambient Declarations](docs/types/ambient/intro.md)\n    * [Declaration Files](docs/types/ambient/d.ts.md)\n    * [Variables](docs/types/ambient/variables.md)\n  * [Interfaces](docs/types/interfaces.md)\n  * [Enums](docs/enums.md)\n  * [`lib.d.ts`](docs/types/lib.d.ts.md)\n  * [Functions](docs/types/functions.md)\n  * [Callable](docs/types/callable.md)\n  * [Type Assertion](docs/types/type-assertion.md)\n  * [Freshness](docs/types/freshness.md)\n  * [Type Guard](docs/types/typeGuard.md)\n  * [Literal Types](docs/types/literal-types.md)\n  * [Readonly](docs/types/readonly.md)\n  * [Generics](docs/types/generics.md)\n  * [Type Inference](docs/types/type-inference.md)\n  * [Type Compatibility](docs/types/type-compatibility.md)\n  * [Never Type](docs/types/never.md)\n  * [Discriminated Unions](docs/types/discriminated-unions.md)\n  * [Index Signatures](docs/types/index-signatures.md)\n  * [Moving Types](docs/types/moving-types.md)\n  * [Exception Handling](docs/types/exceptions.md)\n  * [Mixins](docs/types/mixins.md)\n* [JSX](docs/jsx/tsx.md)\n  * [React](docs/jsx/react.md)\n  * [Non React JSX](docs/jsx/others.md)\n* [Options](docs/options/intro.md)\n  * [noImplicitAny](docs/options/noImplicitAny.md)\n  * [strictNullChecks](docs/options/strictNullChecks.md)\n* [Errors in TypeScript](docs/errors/main.md)\n  * [Interpreting Errors](docs/errors/interpreting-errors.md)\n  * [Common Errors](docs/errors/common-errors.md)\n* [NPM](docs/npm/index.md)\n* [Testing](docs/testing/intro.md)\n  * [Jest](docs/testing/jest.md)\n  * [Cypress](docs/testing/cypress.md)\n* [Tools](docs/tools/intro.md)\n  * [Prettier](docs/tools/prettier.md)\n  * [Husky](docs/tools/husky.md)\n  * [ESLint](docs/tools/eslint.md)\n  * [Changelog](docs/tools/changelog.md)\n* [TIPs](docs/tips/main.md)\n  * [String Based Enums](docs/tips/stringEnums.md)\n  * [Nominal Typing](docs/tips/nominalTyping.md)\n  * [Stateful Functions](docs/tips/statefulFunctions.md)\n  * [Currying](docs/tips/currying.md)\n  * [Type Instantiation](docs/tips/typeInstantiation.md)\n  * [Lazy Object Literal Initialization](docs/tips/lazyObjectLiteralInitialization.md)\n  * [Classes are Useful](docs/tips/classesAreUseful.md)\n  * [Avoid Export Default](docs/tips/defaultIsBad.md)\n  * [Limit Property Setters](docs/tips/propertySetters.md)\n  * [`outFile` caution](docs/tips/outFile.md)\n  * [JQuery tips](docs/tips/jquery.md)\n  * [static constructors](docs/tips/staticConstructor.md)\n  * [singleton pattern](docs/tips/singleton.md)\n  * [Function parameters](docs/tips/functionParameters.md)\n  * [Build Toggles](docs/tips/build-toggles.md)\n  * [Barrel](docs/tips/barrel.md)\n  * [Create Arrays](docs/tips/create-arrays.md)\n  * [Typesafe Event Emitter](docs/tips/typed-event.md)\n* [StyleGuide](docs/styleguide/styleguide.md)\n* [TypeScript Compiler Internals](docs/compiler/overview.md)\n  * [Program](docs/compiler/program.md)\n  * [AST](docs/compiler/ast.md)\n    * [TIP: Visit Children](docs/compiler/ast-tip-children.md)\n    * [TIP: SyntaxKind enum](docs/compiler/ast-tip-syntaxkind.md)\n    * [Trivia](docs/compiler/ast-trivia.md)\n  * [Scanner](docs/compiler/scanner.md)\n  * [Parser](docs/compiler/parser.md)\n    * [Parser Functions](docs/compiler/parser-functions.md)\n  * [Binder](docs/compiler/binder.md)\n    * [Binder Functions](docs/compiler/binder-functions.md)\n    * [Binder Declarations](docs/compiler/binder-declarations.md)\n    * [Binder Container](docs/compiler/binder-container.md)\n    * [Binder SymbolTable](docs/compiler/binder-symboltable.md)\n    * [Binder Error Reporting](docs/compiler/binder-diagnostics.md)\n  * [Checker](docs/compiler/checker.md)\n    * [Checker Diagnostics](docs/compiler/checker-global.md)\n    * [Checker Error Reporting](docs/compiler/checker-diagnostics.md)\n  * [Emitter](docs/compiler/emitter.md)\n    * [Emitter Functions](docs/compiler/emitter-functions.md)\n    * [Emitter SourceMaps](docs/compiler/emitter-sourcemaps.md)\n  * [Contributing](docs/compiler/contributing.md)\n"
  },
  {
    "path": "book.json",
    "content": "{\n  \"language\": \"en\",\n  \"author\": \"Basarat Ali Syed\",\n  \"title\": \"TypeScript Deep Dive\",\n  \"plugins\": [\"edit-link\", \"github\", \"adsense\",\"header\"],\n  \"pluginsConfig\": {\n    \"layout\": {\n      \"headerPath\" : \"header.html\"\n    },\n    \"lunr\": {\n      \"ignoreSpecialCharacters\": true\n    },\n    \"edit-link\": {\n      \"base\": \"https://github.com/basarat/typescript-book/tree/master\",\n      \"label\": \"Edit This Page\"\n    },\n    \"github\": {\n      \"url\": \"https://github.com/basarat/typescript-book/\"\n    },\n    \"adsense\": {\n      \"client\": \"ca-pub-4656761253552116\",\n      \"slot\": \"2017468453\",\n      \"format\": \"auto\",\n      \"element\": \".page-inner section\",\n      \"position\": \"bottom\"\n    }\n  }\n}\n"
  },
  {
    "path": "code/async-await/es5/asyncAwaitES5.js",
    "content": "var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n    return new (P || (P = Promise))(function (resolve, reject) {\n        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n        function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n        step((generator = generator.apply(thisArg, _arguments || [])).next());\n    });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n    return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n    function verb(n) { return function (v) { return step([n, v]); }; }\n    function step(op) {\n        if (f) throw new TypeError(\"Generator is already executing.\");\n        while (_) try {\n            if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n            if (y = 0, t) op = [0, t.value];\n            switch (op[0]) {\n                case 0: case 1: t = op; break;\n                case 4: _.label++; return { value: op[1], done: false };\n                case 5: _.label++; y = op[1]; op = [0]; continue;\n                case 7: op = _.ops.pop(); _.trys.pop(); continue;\n                default:\n                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n                    if (t[2]) _.ops.pop();\n                    _.trys.pop(); continue;\n            }\n            op = body.call(thisArg, _);\n        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n    }\n};\nfunction delay(milliseconds, count) {\n    return new Promise(function (resolve) {\n        setTimeout(function () {\n            resolve(count);\n        }, milliseconds);\n    });\n}\n// async function always return a Promise\nfunction dramaticWelcome() {\n    return __awaiter(this, void 0, void 0, function () {\n        var i, count;\n        return __generator(this, function (_a) {\n            switch (_a.label) {\n                case 0:\n                    console.log(\"Hello\");\n                    i = 0;\n                    _a.label = 1;\n                case 1:\n                    if (!(i < 5)) return [3 /*break*/, 4];\n                    return [4 /*yield*/, delay(500, i)];\n                case 2:\n                    count = _a.sent();\n                    console.log(count);\n                    _a.label = 3;\n                case 3:\n                    i++;\n                    return [3 /*break*/, 1];\n                case 4:\n                    console.log(\"World!\");\n                    return [2 /*return*/];\n            }\n        });\n    });\n}\ndramaticWelcome();\n"
  },
  {
    "path": "code/async-await/es5/asyncAwaitES5.ts",
    "content": "function delay(milliseconds: number, count: number): Promise<number> {\n    return new Promise<number>(resolve => {\n            setTimeout(() => {\n                resolve(count);\n            }, milliseconds);\n        });\n}\n\n// async function always return a Promise\nasync function dramaticWelcome(): Promise<void> {\n    console.log(\"Hello\");\n\n    for (let i = 0; i < 5; i++) {\n        // await is converting Promise<number> into number\n        const count: number = await delay(500, i);\n        console.log(count);\n    }\n\n    console.log(\"World!\");\n}\n\ndramaticWelcome();"
  },
  {
    "path": "code/async-await/es5/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"es5\",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */\n    \"module\": \"commonjs\",                     /* Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'. */\n    \"lib\": [\"dom\", \"es2015.promise\", \"es5\"]  /* Specify library files to be included in the compilation:  */\n  },\n    \"files\": [\n      \"./asyncAwaitES5.ts\"\n  ]\n}"
  },
  {
    "path": "code/async-await/es6/asyncAwaitES6.js",
    "content": "var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n    return new (P || (P = Promise))(function (resolve, reject) {\n        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n        function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n        step((generator = generator.apply(thisArg, _arguments || [])).next());\n    });\n};\nfunction delay(milliseconds, count) {\n    return new Promise(resolve => {\n        setTimeout(() => {\n            resolve(count);\n        }, milliseconds);\n    });\n}\n// async function always return a Promise\nfunction dramaticWelcome() {\n    return __awaiter(this, void 0, void 0, function* () {\n        console.log(\"Hello\");\n        for (let i = 0; i < 5; i++) {\n            // await is converting Promise<number> into number\n            const count = yield delay(500, i);\n            console.log(count);\n        }\n        console.log(\"World!\");\n    });\n}\ndramaticWelcome();\n"
  },
  {
    "path": "code/async-await/es6/asyncAwaitES6.ts",
    "content": "function delay(milliseconds: number, count: number): Promise<number> {\n    return new Promise<number>(resolve => {\n            setTimeout(() => {\n                resolve(count);\n            }, milliseconds);\n        });\n}\n\n// async function always return a Promise\nasync function dramaticWelcome(): Promise<void> {\n    console.log(\"Hello\");\n\n    for (let i = 0; i < 5; i++) {\n        // await is converting Promise<number> into number\n        const count: number = await delay(500, i);\n        console.log(count);\n    }\n\n    console.log(\"World!\");\n}\n\ndramaticWelcome();"
  },
  {
    "path": "code/async-await/es6/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"es6\",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */\n    \"module\": \"commonjs\"                     /* Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'. */\n  },\n    \"files\": [\n      \"./asyncAwaitES6.ts\"\n  ]\n}"
  },
  {
    "path": "code/compiler/package.json",
    "content": "{\n  \"name\": \"compiler\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"runScanner.js\",\n  \"dependencies\": {\n    \"ntypescript\": \"1.201507141013.1\"\n  },\n  \"devDependencies\": {},\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n  },\n  \"author\": \"\",\n  \"license\": \"ISC\"\n}\n"
  },
  {
    "path": "code/compiler/parser/runParser.js",
    "content": "var ts = require(\"ntypescript\");\nfunction printAllChildren(node, depth) {\n    if (depth === void 0) { depth = 0; }\n    console.log(new Array(depth + 1).join('----'), ts.syntaxKindToName(node.kind), node.pos, node.end);\n    depth++;\n    node.getChildren().forEach(function (c) { return printAllChildren(c, depth); });\n}\nvar sourceCode = \"\\nvar foo = 123;\\n\".trim();\nvar sourceFile = ts.createSourceFile('foo.ts', sourceCode, 1, true);\nprintAllChildren(sourceFile);\n"
  },
  {
    "path": "code/compiler/parser/runParser.ts",
    "content": "import * as ts from \"ntypescript\";\n\nfunction printAllChildren(node: ts.Node, depth = 0) {\n    console.log(new Array(depth + 1).join('----'), ts.syntaxKindToName(node.kind), node.pos, node.end);\n    depth++;\n    node.getChildren().forEach(c=> printAllChildren(c, depth));\n}\n\nvar sourceCode = `\nvar foo = 123;\n`.trim();\n\nvar sourceFile = ts.createSourceFile('foo.ts', sourceCode, ts.ScriptTarget.ES5, true);\nprintAllChildren(sourceFile);"
  },
  {
    "path": "code/compiler/scanner/runScanner.js",
    "content": "var ts = require(\"ntypescript\");\nvar scanner = ts.createScanner(2, true);\nfunction initializeState(text) {\n    scanner.setText(text);\n    scanner.setOnError(function (message, length) {\n        console.error(message);\n    });\n    scanner.setScriptTarget(1);\n    scanner.setLanguageVariant(0);\n}\ninitializeState(\"\\nvar foo = 123;\\n\".trim());\nvar token = scanner.scan();\nwhile (token != 1) {\n    console.log(ts.syntaxKindToName(token));\n    token = scanner.scan();\n}\n"
  },
  {
    "path": "code/compiler/scanner/runScanner.ts",
    "content": "import * as ts from \"ntypescript\";\n\n// TypeScript has a singelton scanner\nconst scanner = ts.createScanner(ts.ScriptTarget.Latest, /*skipTrivia*/ true);\n\n// That is initialized using a function `initializeState` similar to\nfunction initializeState(text: string) {\n    scanner.setText(text);\n    scanner.setOnError((message: ts.DiagnosticMessage, length: number) => {\n        console.error(message);\n    });\n    scanner.setScriptTarget(ts.ScriptTarget.ES5);\n    scanner.setLanguageVariant(ts.LanguageVariant.Standard);\n}\n\n// Sample usage\ninitializeState(`\nvar foo = 123;\n`.trim());\n\n// Start the scanning\nvar token = scanner.scan();\nwhile (token != ts.SyntaxKind.EndOfFileToken) {\n    console.log(ts.syntaxKindToName(token));\n    token = scanner.scan();\n}\n"
  },
  {
    "path": "code/compiler/scanner/runScannerWithPositions.js",
    "content": "var ts = require(\"ntypescript\");\nvar scanner = ts.createScanner(2, true);\nfunction initializeState(text) {\n    scanner.setText(text);\n    scanner.setOnError(function (message, length) {\n        console.error(message);\n    });\n    scanner.setScriptTarget(1);\n    scanner.setLanguageVariant(0);\n}\ninitializeState(\"\\nvar foo = 123;\\n\".trim());\nvar token = scanner.scan();\nwhile (token != 1) {\n    var currentToken = ts.syntaxKindToName(token);\n    var tokenStart = scanner.getStartPos();\n    token = scanner.scan();\n    var tokenEnd = scanner.getStartPos();\n    console.log(currentToken, tokenStart, tokenEnd);\n}\n"
  },
  {
    "path": "code/compiler/scanner/runScannerWithPositions.ts",
    "content": "import * as ts from \"ntypescript\";\n\n// TypeScript has a singelton scanner\nconst scanner = ts.createScanner(ts.ScriptTarget.Latest, /*skipTrivia*/ true);\n\n// That is initialized using a function `initializeState` similar to\nfunction initializeState(text: string) {\n    scanner.setText(text);\n    scanner.setOnError((message: ts.DiagnosticMessage, length: number) => {\n        console.error(message);\n    });\n    scanner.setScriptTarget(ts.ScriptTarget.ES5);\n    scanner.setLanguageVariant(ts.LanguageVariant.Standard);\n}\n\n// Sample usage\ninitializeState(`\nvar foo = 123;\n`.trim());\n\n// Start the scanning\nvar token = scanner.scan();\nwhile (token != ts.SyntaxKind.EndOfFileToken) {\n    let currentToken = ts.syntaxKindToName(token);\n    let tokenStart = scanner.getStartPos();\n    token = scanner.scan();\n    let tokenEnd = scanner.getStartPos();\n    console.log(currentToken, tokenStart, tokenEnd);\n}\n"
  },
  {
    "path": "code/compiler/tsconfig.json",
    "content": "{\n    \"version\": \"1.5.0-beta\",\n    \"compilerOptions\": {\n        \"target\": \"es5\",\n        \"module\": \"commonjs\",\n        \"isolatedModules\": false,\n        \"jsx\": \"react\",\n        \"experimentalDecorators\": true,\n        \"emitDecoratorMetadata\": true,\n        \"declaration\": false,\n        \"noImplicitAny\": false,\n        \"removeComments\": true,\n        \"noLib\": false,\n        \"preserveConstEnums\": true,\n        \"suppressImplicitAnyIndexErrors\": true\n    },\n    \"filesGlob\": [\n        \"./**/*.ts\",\n        \"./**/*.tsx\",\n        \"!./node_modules/**/*\"\n    ],\n    \"files\": [\n        \"./parser/runParser.ts\",\n        \"./scanner/runScanner.ts\",\n        \"./scanner/runScannerWithPositions.ts\",\n        \"./typings/node/node.d.ts\",\n        \"./typings/tsd.d.ts\"\n    ]\n}\n"
  },
  {
    "path": "code/compiler/tsd.json",
    "content": "{\n  \"version\": \"v4\",\n  \"repo\": \"borisyankov/DefinitelyTyped\",\n  \"ref\": \"master\",\n  \"path\": \"typings\",\n  \"bundle\": \"typings/tsd.d.ts\",\n  \"installed\": {\n    \"node/node.d.ts\": {\n      \"commit\": \"38c6ccfde0e67ff10d7408e0ee8b7720b3f21d3b\"\n    }\n  }\n}\n"
  },
  {
    "path": "code/compiler/typings/node/node.d.ts",
    "content": "// Type definitions for Node.js v0.12.0\n// Project: http://nodejs.org/\n// Definitions by: Microsoft TypeScript <http://typescriptlang.org>, DefinitelyTyped <https://github.com/borisyankov/DefinitelyTyped>\n// Definitions: https://github.com/borisyankov/DefinitelyTyped\n\n/************************************************\n*                                               *\n*               Node.js v0.12.0 API             *\n*                                               *\n************************************************/\n\n/************************************************\n*                                               *\n*                   GLOBAL                      *\n*                                               *\n************************************************/\ndeclare var process: NodeJS.Process;\ndeclare var global: NodeJS.Global;\n\ndeclare var __filename: string;\ndeclare var __dirname: string;\n\ndeclare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer;\ndeclare function clearTimeout(timeoutId: NodeJS.Timer): void;\ndeclare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer;\ndeclare function clearInterval(intervalId: NodeJS.Timer): void;\ndeclare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any;\ndeclare function clearImmediate(immediateId: any): void;\n\ndeclare var require: {\n    (id: string): any;\n    resolve(id:string): string;\n    cache: any;\n    extensions: any;\n    main: any;\n};\n\ndeclare var module: {\n    exports: any;\n    require(id: string): any;\n    id: string;\n    filename: string;\n    loaded: boolean;\n    parent: any;\n    children: any[];\n};\n\n// Same as module.exports\ndeclare var exports: any;\ndeclare var SlowBuffer: {\n    new (str: string, encoding?: string): Buffer;\n    new (size: number): Buffer;\n    new (size: Uint8Array): Buffer;\n    new (array: any[]): Buffer;\n    prototype: Buffer;\n    isBuffer(obj: any): boolean;\n    byteLength(string: string, encoding?: string): number;\n    concat(list: Buffer[], totalLength?: number): Buffer;\n};\n\n\n// Buffer class\ninterface Buffer extends NodeBuffer {}\n\n/**\n * Raw data is stored in instances of the Buffer class.\n * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap.  A Buffer cannot be resized.\n * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex'\n */\ndeclare var Buffer: {\n    /**\n     * Allocates a new buffer containing the given {str}.\n     *\n     * @param str String to store in buffer.\n     * @param encoding encoding to use, optional.  Default is 'utf8'\n     */\n    new (str: string, encoding?: string): Buffer;\n    /**\n     * Allocates a new buffer of {size} octets.\n     *\n     * @param size count of octets to allocate.\n     */\n    new (size: number): Buffer;\n    /**\n     * Allocates a new buffer containing the given {array} of octets.\n     *\n     * @param array The octets to store.\n     */\n    new (array: Uint8Array): Buffer;\n    /**\n     * Allocates a new buffer containing the given {array} of octets.\n     *\n     * @param array The octets to store.\n     */\n    new (array: any[]): Buffer;\n    prototype: Buffer;\n    /**\n     * Returns true if {obj} is a Buffer\n     *\n     * @param obj object to test.\n     */\n    isBuffer(obj: any): boolean;\n    /**\n     * Returns true if {encoding} is a valid encoding argument.\n     * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex'\n     *\n     * @param encoding string to test.\n     */\n    isEncoding(encoding: string): boolean;\n    /**\n     * Gives the actual byte length of a string. encoding defaults to 'utf8'.\n     * This is not the same as String.prototype.length since that returns the number of characters in a string.\n     *\n     * @param string string to test.\n     * @param encoding encoding used to evaluate (defaults to 'utf8')\n     */\n    byteLength(string: string, encoding?: string): number;\n    /**\n     * Returns a buffer which is the result of concatenating all the buffers in the list together.\n     *\n     * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer.\n     * If the list has exactly one item, then the first item of the list is returned.\n     * If the list has more than one item, then a new Buffer is created.\n     *\n     * @param list An array of Buffer objects to concatenate\n     * @param totalLength Total length of the buffers when concatenated.\n     *   If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly.\n     */\n    concat(list: Buffer[], totalLength?: number): Buffer;\n    /**\n     * The same as buf1.compare(buf2).\n     */\n    compare(buf1: Buffer, buf2: Buffer): number;\n};\n\n/************************************************\n*                                               *\n*               GLOBAL INTERFACES               *\n*                                               *\n************************************************/\ndeclare module NodeJS {\n    export interface ErrnoException extends Error {\n        errno?: number;\n        code?: string;\n        path?: string;\n        syscall?: string;\n        stack?: string;\n    }\n\n    export interface EventEmitter {\n        addListener(event: string, listener: Function): EventEmitter;\n        on(event: string, listener: Function): EventEmitter;\n        once(event: string, listener: Function): EventEmitter;\n        removeListener(event: string, listener: Function): EventEmitter;\n        removeAllListeners(event?: string): EventEmitter;\n        setMaxListeners(n: number): void;\n        listeners(event: string): Function[];\n        emit(event: string, ...args: any[]): boolean;\n    }\n\n    export interface ReadableStream extends EventEmitter {\n        readable: boolean;\n        read(size?: number): string|Buffer;\n        setEncoding(encoding: string): void;\n        pause(): void;\n        resume(): void;\n        pipe<T extends WritableStream>(destination: T, options?: { end?: boolean; }): T;\n        unpipe<T extends WritableStream>(destination?: T): void;\n        unshift(chunk: string): void;\n        unshift(chunk: Buffer): void;\n        wrap(oldStream: ReadableStream): ReadableStream;\n    }\n\n    export interface WritableStream extends EventEmitter {\n        writable: boolean;\n        write(buffer: Buffer, cb?: Function): boolean;\n        write(str: string, cb?: Function): boolean;\n        write(str: string, encoding?: string, cb?: Function): boolean;\n        end(): void;\n        end(buffer: Buffer, cb?: Function): void;\n        end(str: string, cb?: Function): void;\n        end(str: string, encoding?: string, cb?: Function): void;\n    }\n\n    export interface ReadWriteStream extends ReadableStream, WritableStream {}\n\n    export interface Process extends EventEmitter {\n        stdout: WritableStream;\n        stderr: WritableStream;\n        stdin: ReadableStream;\n        argv: string[];\n        execPath: string;\n        abort(): void;\n        chdir(directory: string): void;\n        cwd(): string;\n        env: any;\n        exit(code?: number): void;\n        getgid(): number;\n        setgid(id: number): void;\n        setgid(id: string): void;\n        getuid(): number;\n        setuid(id: number): void;\n        setuid(id: string): void;\n        version: string;\n        versions: {\n            http_parser: string;\n            node: string;\n            v8: string;\n            ares: string;\n            uv: string;\n            zlib: string;\n            openssl: string;\n        };\n        config: {\n            target_defaults: {\n                cflags: any[];\n                default_configuration: string;\n                defines: string[];\n                include_dirs: string[];\n                libraries: string[];\n            };\n            variables: {\n                clang: number;\n                host_arch: string;\n                node_install_npm: boolean;\n                node_install_waf: boolean;\n                node_prefix: string;\n                node_shared_openssl: boolean;\n                node_shared_v8: boolean;\n                node_shared_zlib: boolean;\n                node_use_dtrace: boolean;\n                node_use_etw: boolean;\n                node_use_openssl: boolean;\n                target_arch: string;\n                v8_no_strict_aliasing: number;\n                v8_use_snapshot: boolean;\n                visibility: string;\n            };\n        };\n        kill(pid: number, signal?: string): void;\n        pid: number;\n        title: string;\n        arch: string;\n        platform: string;\n        memoryUsage(): { rss: number; heapTotal: number; heapUsed: number; };\n        nextTick(callback: Function): void;\n        umask(mask?: number): number;\n        uptime(): number;\n        hrtime(time?:number[]): number[];\n\n        // Worker\n        send?(message: any, sendHandle?: any): void;\n    }\n\n    export interface Global {\n        Array: typeof Array;\n        ArrayBuffer: typeof ArrayBuffer;\n        Boolean: typeof Boolean;\n        Buffer: typeof Buffer;\n        DataView: typeof DataView;\n        Date: typeof Date;\n        Error: typeof Error;\n        EvalError: typeof EvalError;\n        Float32Array: typeof Float32Array;\n        Float64Array: typeof Float64Array;\n        Function: typeof Function;\n        GLOBAL: Global;\n        Infinity: typeof Infinity;\n        Int16Array: typeof Int16Array;\n        Int32Array: typeof Int32Array;\n        Int8Array: typeof Int8Array;\n        Intl: typeof Intl;\n        JSON: typeof JSON;\n        Map: typeof Map;\n        Math: typeof Math;\n        NaN: typeof NaN;\n        Number: typeof Number;\n        Object: typeof Object;\n        Promise: Function;\n        RangeError: typeof RangeError;\n        ReferenceError: typeof ReferenceError;\n        RegExp: typeof RegExp;\n        Set: typeof Set;\n        String: typeof String;\n        Symbol: Function;\n        SyntaxError: typeof SyntaxError;\n        TypeError: typeof TypeError;\n        URIError: typeof URIError;\n        Uint16Array: typeof Uint16Array;\n        Uint32Array: typeof Uint32Array;\n        Uint8Array: typeof Uint8Array;\n        Uint8ClampedArray: Function;\n        WeakMap: typeof WeakMap;\n        WeakSet: Function;\n        clearImmediate: (immediateId: any) => void;\n        clearInterval: (intervalId: NodeJS.Timer) => void;\n        clearTimeout: (timeoutId: NodeJS.Timer) => void;\n        console: typeof console;\n        decodeURI: typeof decodeURI;\n        decodeURIComponent: typeof decodeURIComponent;\n        encodeURI: typeof encodeURI;\n        encodeURIComponent: typeof encodeURIComponent;\n        escape: (str: string) => string;\n        eval: typeof eval;\n        global: Global;\n        isFinite: typeof isFinite;\n        isNaN: typeof isNaN;\n        parseFloat: typeof parseFloat;\n        parseInt: typeof parseInt;\n        process: Process;\n        root: Global;\n        setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any;\n        setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer;\n        setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer;\n        undefined: typeof undefined;\n        unescape: (str: string) => string;\n        gc: () => void;\n    }\n\n    export interface Timer {\n        ref() : void;\n        unref() : void;\n    }\n}\n\n/**\n * @deprecated\n */\ninterface NodeBuffer {\n    [index: number]: number;\n    write(string: string, offset?: number, length?: number, encoding?: string): number;\n    toString(encoding?: string, start?: number, end?: number): string;\n    toJSON(): any;\n    length: number;\n    equals(otherBuffer: Buffer): boolean;\n    compare(otherBuffer: Buffer): number;\n    copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;\n    slice(start?: number, end?: number): Buffer;\n    writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;\n    writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;\n    writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;\n    writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;\n    readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number;\n    readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number;\n    readIntLE(offset: number, byteLength: number, noAssert?: boolean): number;\n    readIntBE(offset: number, byteLength: number, noAssert?: boolean): number;\n    readUInt8(offset: number, noAsset?: boolean): number;\n    readUInt16LE(offset: number, noAssert?: boolean): number;\n    readUInt16BE(offset: number, noAssert?: boolean): number;\n    readUInt32LE(offset: number, noAssert?: boolean): number;\n    readUInt32BE(offset: number, noAssert?: boolean): number;\n    readInt8(offset: number, noAssert?: boolean): number;\n    readInt16LE(offset: number, noAssert?: boolean): number;\n    readInt16BE(offset: number, noAssert?: boolean): number;\n    readInt32LE(offset: number, noAssert?: boolean): number;\n    readInt32BE(offset: number, noAssert?: boolean): number;\n    readFloatLE(offset: number, noAssert?: boolean): number;\n    readFloatBE(offset: number, noAssert?: boolean): number;\n    readDoubleLE(offset: number, noAssert?: boolean): number;\n    readDoubleBE(offset: number, noAssert?: boolean): number;\n    writeUInt8(value: number, offset: number, noAssert?: boolean): void;\n    writeUInt16LE(value: number, offset: number, noAssert?: boolean): void;\n    writeUInt16BE(value: number, offset: number, noAssert?: boolean): void;\n    writeUInt32LE(value: number, offset: number, noAssert?: boolean): void;\n    writeUInt32BE(value: number, offset: number, noAssert?: boolean): void;\n    writeInt8(value: number, offset: number, noAssert?: boolean): void;\n    writeInt16LE(value: number, offset: number, noAssert?: boolean): void;\n    writeInt16BE(value: number, offset: number, noAssert?: boolean): void;\n    writeInt32LE(value: number, offset: number, noAssert?: boolean): void;\n    writeInt32BE(value: number, offset: number, noAssert?: boolean): void;\n    writeFloatLE(value: number, offset: number, noAssert?: boolean): void;\n    writeFloatBE(value: number, offset: number, noAssert?: boolean): void;\n    writeDoubleLE(value: number, offset: number, noAssert?: boolean): void;\n    writeDoubleBE(value: number, offset: number, noAssert?: boolean): void;\n    fill(value: any, offset?: number, end?: number): void;\n}\n\n/************************************************\n*                                               *\n*                   MODULES                     *\n*                                               *\n************************************************/\ndeclare module \"buffer\" {\n    export var INSPECT_MAX_BYTES: number;\n}\n\ndeclare module \"querystring\" {\n    export function stringify(obj: any, sep?: string, eq?: string): string;\n    export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any;\n    export function escape(str: string): string;\n    export function unescape(str: string): string;\n}\n\ndeclare module \"events\" {\n    export class EventEmitter implements NodeJS.EventEmitter {\n        static listenerCount(emitter: EventEmitter, event: string): number;\n\n        addListener(event: string, listener: Function): EventEmitter;\n        on(event: string, listener: Function): EventEmitter;\n        once(event: string, listener: Function): EventEmitter;\n        removeListener(event: string, listener: Function): EventEmitter;\n        removeAllListeners(event?: string): EventEmitter;\n        setMaxListeners(n: number): void;\n        listeners(event: string): Function[];\n        emit(event: string, ...args: any[]): boolean;\n   }\n}\n\ndeclare module \"http\" {\n    import events = require(\"events\");\n    import net = require(\"net\");\n    import stream = require(\"stream\");\n\n    export interface Server extends events.EventEmitter {\n        listen(port: number, hostname?: string, backlog?: number, callback?: Function): Server;\n        listen(port: number, hostname?: string, callback?: Function): Server;\n        listen(path: string, callback?: Function): Server;\n        listen(handle: any, listeningListener?: Function): Server;\n        close(cb?: any): Server;\n        address(): { port: number; family: string; address: string; };\n        maxHeadersCount: number;\n    }\n    /**\n     * @deprecated Use IncomingMessage\n     */\n    export interface ServerRequest extends IncomingMessage {\n        connection: net.Socket;\n    }\n    export interface ServerResponse extends events.EventEmitter, stream.Writable {\n        // Extended base methods\n        write(buffer: Buffer): boolean;\n        write(buffer: Buffer, cb?: Function): boolean;\n        write(str: string, cb?: Function): boolean;\n        write(str: string, encoding?: string, cb?: Function): boolean;\n        write(str: string, encoding?: string, fd?: string): boolean;\n\n        writeContinue(): void;\n        writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void;\n        writeHead(statusCode: number, headers?: any): void;\n        statusCode: number;\n        setHeader(name: string, value: string): void;\n        sendDate: boolean;\n        getHeader(name: string): string;\n        removeHeader(name: string): void;\n        write(chunk: any, encoding?: string): any;\n        addTrailers(headers: any): void;\n\n        // Extended base methods\n        end(): void;\n        end(buffer: Buffer, cb?: Function): void;\n        end(str: string, cb?: Function): void;\n        end(str: string, encoding?: string, cb?: Function): void;\n        end(data?: any, encoding?: string): void;\n    }\n    export interface ClientRequest extends events.EventEmitter, stream.Writable {\n        // Extended base methods\n        write(buffer: Buffer): boolean;\n        write(buffer: Buffer, cb?: Function): boolean;\n        write(str: string, cb?: Function): boolean;\n        write(str: string, encoding?: string, cb?: Function): boolean;\n        write(str: string, encoding?: string, fd?: string): boolean;\n\n        write(chunk: any, encoding?: string): void;\n        abort(): void;\n        setTimeout(timeout: number, callback?: Function): void;\n        setNoDelay(noDelay?: boolean): void;\n        setSocketKeepAlive(enable?: boolean, initialDelay?: number): void;\n\n        // Extended base methods\n        end(): void;\n        end(buffer: Buffer, cb?: Function): void;\n        end(str: string, cb?: Function): void;\n        end(str: string, encoding?: string, cb?: Function): void;\n        end(data?: any, encoding?: string): void;\n    }\n    export interface IncomingMessage extends events.EventEmitter, stream.Readable {\n        httpVersion: string;\n        headers: any;\n        rawHeaders: string[];\n        trailers: any;\n        rawTrailers: any;\n        setTimeout(msecs: number, callback: Function): NodeJS.Timer;\n        /**\n         * Only valid for request obtained from http.Server.\n         */\n        method?: string;\n        /**\n         * Only valid for request obtained from http.Server.\n         */\n        url?: string;\n        /**\n         * Only valid for response obtained from http.ClientRequest.\n         */\n        statusCode?: number;\n        /**\n         * Only valid for response obtained from http.ClientRequest.\n         */\n        statusMessage?: string;\n        socket: net.Socket;\n    }\n    /**\n     * @deprecated Use IncomingMessage\n     */\n    export interface ClientResponse extends IncomingMessage { }\n\n\texport interface AgentOptions {\n\t\t/**\n\t\t * Keep sockets around in a pool to be used by other requests in the future. Default = false\n\t\t */\n\t\tkeepAlive?: boolean;\n\t\t/**\n\t\t * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000.\n\t\t * Only relevant if keepAlive is set to true.\n\t\t */\n\t\tkeepAliveMsecs?: number;\n\t\t/**\n\t\t * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity\n\t\t */\n\t\tmaxSockets?: number;\n\t\t/**\n\t\t * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256.\n\t\t */\n\t\tmaxFreeSockets?: number;\n\t}\n\n    export class Agent {\n\t\tmaxSockets: number;\n\t\tsockets: any;\n\t\trequests: any;\n\n\t\tconstructor(opts?: AgentOptions);\n\n\t\t/**\n\t\t * Destroy any sockets that are currently in use by the agent.\n\t\t * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled,\n\t\t * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise,\n\t\t * sockets may hang open for quite a long time before the server terminates them.\n\t\t */\n\t\tdestroy(): void;\n\t}\n\n    export var METHODS: string[];\n\n    export var STATUS_CODES: {\n        [errorCode: number]: string;\n        [errorCode: string]: string;\n    };\n    export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) =>void ): Server;\n    export function createClient(port?: number, host?: string): any;\n    export function request(options: any, callback?: (res: IncomingMessage) => void): ClientRequest;\n    export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest;\n    export var globalAgent: Agent;\n}\n\ndeclare module \"cluster\" {\n    import child  = require(\"child_process\");\n    import events = require(\"events\");\n\n    export interface ClusterSettings {\n        exec?: string;\n        args?: string[];\n        silent?: boolean;\n    }\n\n    export class Worker extends events.EventEmitter {\n        id: string;\n        process: child.ChildProcess;\n        suicide: boolean;\n        send(message: any, sendHandle?: any): void;\n        kill(signal?: string): void;\n        destroy(signal?: string): void;\n        disconnect(): void;\n    }\n\n    export var settings: ClusterSettings;\n    export var isMaster: boolean;\n    export var isWorker: boolean;\n    export function setupMaster(settings?: ClusterSettings): void;\n    export function fork(env?: any): Worker;\n    export function disconnect(callback?: Function): void;\n    export var worker: Worker;\n    export var workers: Worker[];\n\n    // Event emitter\n    export function addListener(event: string, listener: Function): void;\n    export function on(event: string, listener: Function): any;\n    export function once(event: string, listener: Function): void;\n    export function removeListener(event: string, listener: Function): void;\n    export function removeAllListeners(event?: string): void;\n    export function setMaxListeners(n: number): void;\n    export function listeners(event: string): Function[];\n    export function emit(event: string, ...args: any[]): boolean;\n}\n\ndeclare module \"zlib\" {\n    import stream = require(\"stream\");\n    export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; }\n\n    export interface Gzip extends stream.Transform { }\n    export interface Gunzip extends stream.Transform { }\n    export interface Deflate extends stream.Transform { }\n    export interface Inflate extends stream.Transform { }\n    export interface DeflateRaw extends stream.Transform { }\n    export interface InflateRaw extends stream.Transform { }\n    export interface Unzip extends stream.Transform { }\n\n    export function createGzip(options?: ZlibOptions): Gzip;\n    export function createGunzip(options?: ZlibOptions): Gunzip;\n    export function createDeflate(options?: ZlibOptions): Deflate;\n    export function createInflate(options?: ZlibOptions): Inflate;\n    export function createDeflateRaw(options?: ZlibOptions): DeflateRaw;\n    export function createInflateRaw(options?: ZlibOptions): InflateRaw;\n    export function createUnzip(options?: ZlibOptions): Unzip;\n\n    export function deflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void;\n    export function deflateSync(buf: Buffer, options?: ZlibOptions): any;\n    export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void;\n    export function deflateRawSync(buf: Buffer, options?: ZlibOptions): any;\n    export function gzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void;\n    export function gzipSync(buf: Buffer, options?: ZlibOptions): any;\n    export function gunzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void;\n    export function gunzipSync(buf: Buffer, options?: ZlibOptions): any;\n    export function inflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void;\n    export function inflateSync(buf: Buffer, options?: ZlibOptions): any;\n    export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void;\n    export function inflateRawSync(buf: Buffer, options?: ZlibOptions): any;\n    export function unzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void;\n    export function unzipSync(buf: Buffer, options?: ZlibOptions): any;\n\n    // Constants\n    export var Z_NO_FLUSH: number;\n    export var Z_PARTIAL_FLUSH: number;\n    export var Z_SYNC_FLUSH: number;\n    export var Z_FULL_FLUSH: number;\n    export var Z_FINISH: number;\n    export var Z_BLOCK: number;\n    export var Z_TREES: number;\n    export var Z_OK: number;\n    export var Z_STREAM_END: number;\n    export var Z_NEED_DICT: number;\n    export var Z_ERRNO: number;\n    export var Z_STREAM_ERROR: number;\n    export var Z_DATA_ERROR: number;\n    export var Z_MEM_ERROR: number;\n    export var Z_BUF_ERROR: number;\n    export var Z_VERSION_ERROR: number;\n    export var Z_NO_COMPRESSION: number;\n    export var Z_BEST_SPEED: number;\n    export var Z_BEST_COMPRESSION: number;\n    export var Z_DEFAULT_COMPRESSION: number;\n    export var Z_FILTERED: number;\n    export var Z_HUFFMAN_ONLY: number;\n    export var Z_RLE: number;\n    export var Z_FIXED: number;\n    export var Z_DEFAULT_STRATEGY: number;\n    export var Z_BINARY: number;\n    export var Z_TEXT: number;\n    export var Z_ASCII: number;\n    export var Z_UNKNOWN: number;\n    export var Z_DEFLATED: number;\n    export var Z_NULL: number;\n}\n\ndeclare module \"os\" {\n    export function tmpdir(): string;\n    export function hostname(): string;\n    export function type(): string;\n    export function platform(): string;\n    export function arch(): string;\n    export function release(): string;\n    export function uptime(): number;\n    export function loadavg(): number[];\n    export function totalmem(): number;\n    export function freemem(): number;\n    export function cpus(): { model: string; speed: number; times: { user: number; nice: number; sys: number; idle: number; irq: number; }; }[];\n    export function networkInterfaces(): any;\n    export var EOL: string;\n}\n\ndeclare module \"https\" {\n    import tls = require(\"tls\");\n    import events = require(\"events\");\n    import http = require(\"http\");\n\n    export interface ServerOptions {\n        pfx?: any;\n        key?: any;\n        passphrase?: string;\n        cert?: any;\n        ca?: any;\n        crl?: any;\n        ciphers?: string;\n        honorCipherOrder?: boolean;\n        requestCert?: boolean;\n        rejectUnauthorized?: boolean;\n        NPNProtocols?: any;\n        SNICallback?: (servername: string) => any;\n    }\n\n    export interface RequestOptions {\n        host?: string;\n        hostname?: string;\n        port?: number;\n        path?: string;\n        method?: string;\n        headers?: any;\n        auth?: string;\n        agent?: any;\n        pfx?: any;\n        key?: any;\n        passphrase?: string;\n        cert?: any;\n        ca?: any;\n        ciphers?: string;\n        rejectUnauthorized?: boolean;\n    }\n\n    export interface Agent {\n        maxSockets: number;\n        sockets: any;\n        requests: any;\n    }\n    export var Agent: {\n        new (options?: RequestOptions): Agent;\n    };\n    export interface Server extends tls.Server { }\n    export function createServer(options: ServerOptions, requestListener?: Function): Server;\n    export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest;\n    export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest;\n    export var globalAgent: Agent;\n}\n\ndeclare module \"punycode\" {\n    export function decode(string: string): string;\n    export function encode(string: string): string;\n    export function toUnicode(domain: string): string;\n    export function toASCII(domain: string): string;\n    export var ucs2: ucs2;\n    interface ucs2 {\n        decode(string: string): string;\n        encode(codePoints: number[]): string;\n    }\n    export var version: any;\n}\n\ndeclare module \"repl\" {\n    import stream = require(\"stream\");\n    import events = require(\"events\");\n\n    export interface ReplOptions {\n        prompt?: string;\n        input?: NodeJS.ReadableStream;\n        output?: NodeJS.WritableStream;\n        terminal?: boolean;\n        eval?: Function;\n        useColors?: boolean;\n        useGlobal?: boolean;\n        ignoreUndefined?: boolean;\n        writer?: Function;\n    }\n    export function start(options: ReplOptions): events.EventEmitter;\n}\n\ndeclare module \"readline\" {\n    import events = require(\"events\");\n    import stream = require(\"stream\");\n\n    export interface ReadLine extends events.EventEmitter {\n        setPrompt(prompt: string, length: number): void;\n        prompt(preserveCursor?: boolean): void;\n        question(query: string, callback: Function): void;\n        pause(): void;\n        resume(): void;\n        close(): void;\n        write(data: any, key?: any): void;\n    }\n    export interface ReadLineOptions {\n        input: NodeJS.ReadableStream;\n        output: NodeJS.WritableStream;\n        completer?: Function;\n        terminal?: boolean;\n    }\n    export function createInterface(options: ReadLineOptions): ReadLine;\n}\n\ndeclare module \"vm\" {\n    export interface Context { }\n    export interface Script {\n        runInThisContext(): void;\n        runInNewContext(sandbox?: Context): void;\n    }\n    export function runInThisContext(code: string, filename?: string): void;\n    export function runInNewContext(code: string, sandbox?: Context, filename?: string): void;\n    export function runInContext(code: string, context: Context, filename?: string): void;\n    export function createContext(initSandbox?: Context): Context;\n    export function createScript(code: string, filename?: string): Script;\n}\n\ndeclare module \"child_process\" {\n    import events = require(\"events\");\n    import stream = require(\"stream\");\n\n    export interface ChildProcess extends events.EventEmitter {\n        stdin:  stream.Writable;\n        stdout: stream.Readable;\n        stderr: stream.Readable;\n        pid: number;\n        kill(signal?: string): void;\n        send(message: any, sendHandle?: any): void;\n        disconnect(): void;\n    }\n\n    export function spawn(command: string, args?: string[], options?: {\n        cwd?: string;\n        stdio?: any;\n        custom?: any;\n        env?: any;\n        detached?: boolean;\n    }): ChildProcess;\n    export function exec(command: string, options: {\n        cwd?: string;\n        stdio?: any;\n        customFds?: any;\n        env?: any;\n        encoding?: string;\n        timeout?: number;\n        maxBuffer?: number;\n        killSignal?: string;\n    }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;\n    export function exec(command: string, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;\n    export function execFile(file: string,\n        callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;\n    export function execFile(file: string, args?: string[],\n        callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;\n    export function execFile(file: string, args?: string[], options?: {\n        cwd?: string;\n        stdio?: any;\n        customFds?: any;\n        env?: any;\n        encoding?: string;\n        timeout?: number;\n        maxBuffer?: string;\n        killSignal?: string;\n    }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;\n    export function fork(modulePath: string, args?: string[], options?: {\n        cwd?: string;\n        env?: any;\n        encoding?: string;\n    }): ChildProcess;\n    export function execSync(command: string, options?: {\n        cwd?: string;\n        input?: string|Buffer;\n        stdio?: any;\n        env?: any;\n        uid?: number;\n        gid?: number;\n        timeout?: number;\n        maxBuffer?: number;\n        killSignal?: string;\n        encoding?: string;\n    }): ChildProcess;\n    export function execFileSync(command: string, args?: string[], options?: {\n        cwd?: string;\n        input?: string|Buffer;\n        stdio?: any;\n        env?: any;\n        uid?: number;\n        gid?: number;\n        timeout?: number;\n        maxBuffer?: number;\n        killSignal?: string;\n        encoding?: string;\n    }): ChildProcess;\n}\n\ndeclare module \"url\" {\n    export interface Url {\n        href: string;\n        protocol: string;\n        auth: string;\n        hostname: string;\n        port: string;\n        host: string;\n        pathname: string;\n        search: string;\n        query: any; // string | Object\n        slashes: boolean;\n        hash?: string;\n        path?: string;\n    }\n\n    export interface UrlOptions {\n        protocol?: string;\n        auth?: string;\n        hostname?: string;\n        port?: string;\n        host?: string;\n        pathname?: string;\n        search?: string;\n        query?: any;\n        hash?: string;\n        path?: string;\n    }\n\n    export function parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url;\n    export function format(url: UrlOptions): string;\n    export function resolve(from: string, to: string): string;\n}\n\ndeclare module \"dns\" {\n    export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string;\n    export function lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string;\n    export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) =>void ): string[];\n    export function resolve(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];\n    export function resolve4(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];\n    export function resolve6(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];\n    export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];\n    export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];\n    export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];\n    export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];\n    export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];\n    export function reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[];\n}\n\ndeclare module \"net\" {\n    import stream = require(\"stream\");\n\n    export interface Socket extends stream.Duplex {\n        // Extended base methods\n        write(buffer: Buffer): boolean;\n        write(buffer: Buffer, cb?: Function): boolean;\n        write(str: string, cb?: Function): boolean;\n        write(str: string, encoding?: string, cb?: Function): boolean;\n        write(str: string, encoding?: string, fd?: string): boolean;\n\n        connect(port: number, host?: string, connectionListener?: Function): void;\n        connect(path: string, connectionListener?: Function): void;\n        bufferSize: number;\n        setEncoding(encoding?: string): void;\n        write(data: any, encoding?: string, callback?: Function): void;\n        destroy(): void;\n        pause(): void;\n        resume(): void;\n        setTimeout(timeout: number, callback?: Function): void;\n        setNoDelay(noDelay?: boolean): void;\n        setKeepAlive(enable?: boolean, initialDelay?: number): void;\n        address(): { port: number; family: string; address: string; };\n        unref(): void;\n        ref(): void;\n\n        remoteAddress: string;\n        remoteFamily: string;\n        remotePort: number;\n        localAddress: string;\n        localPort: number;\n        bytesRead: number;\n        bytesWritten: number;\n\n        // Extended base methods\n        end(): void;\n        end(buffer: Buffer, cb?: Function): void;\n        end(str: string, cb?: Function): void;\n        end(str: string, encoding?: string, cb?: Function): void;\n        end(data?: any, encoding?: string): void;\n    }\n\n    export var Socket: {\n        new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket;\n    };\n\n    export interface Server extends Socket {\n        listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server;\n        listen(path: string, listeningListener?: Function): Server;\n        listen(handle: any, listeningListener?: Function): Server;\n        close(callback?: Function): Server;\n        address(): { port: number; family: string; address: string; };\n        maxConnections: number;\n        connections: number;\n    }\n    export function createServer(connectionListener?: (socket: Socket) =>void ): Server;\n    export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) =>void ): Server;\n    export function connect(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): Socket;\n    export function connect(port: number, host?: string, connectionListener?: Function): Socket;\n    export function connect(path: string, connectionListener?: Function): Socket;\n    export function createConnection(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): Socket;\n    export function createConnection(port: number, host?: string, connectionListener?: Function): Socket;\n    export function createConnection(path: string, connectionListener?: Function): Socket;\n    export function isIP(input: string): number;\n    export function isIPv4(input: string): boolean;\n    export function isIPv6(input: string): boolean;\n}\n\ndeclare module \"dgram\" {\n    import events = require(\"events\");\n\n    interface RemoteInfo {\n        address: string;\n        port: number;\n        size: number;\n    }\n\n    interface AddressInfo {\n        address: string;\n        family: string;\n        port: number;\n    }\n\n    export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket;\n\n    interface Socket extends events.EventEmitter {\n        send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void;\n        bind(port: number, address?: string, callback?: () => void): void;\n        close(): void;\n        address(): AddressInfo;\n        setBroadcast(flag: boolean): void;\n        setMulticastTTL(ttl: number): void;\n        setMulticastLoopback(flag: boolean): void;\n        addMembership(multicastAddress: string, multicastInterface?: string): void;\n        dropMembership(multicastAddress: string, multicastInterface?: string): void;\n    }\n}\n\ndeclare module \"fs\" {\n    import stream = require(\"stream\");\n    import events = require(\"events\");\n\n    interface Stats {\n        isFile(): boolean;\n        isDirectory(): boolean;\n        isBlockDevice(): boolean;\n        isCharacterDevice(): boolean;\n        isSymbolicLink(): boolean;\n        isFIFO(): boolean;\n        isSocket(): boolean;\n        dev: number;\n        ino: number;\n        mode: number;\n        nlink: number;\n        uid: number;\n        gid: number;\n        rdev: number;\n        size: number;\n        blksize: number;\n        blocks: number;\n        atime: Date;\n        mtime: Date;\n        ctime: Date;\n    }\n\n    interface FSWatcher extends events.EventEmitter {\n        close(): void;\n    }\n\n    export interface ReadStream extends stream.Readable {\n        close(): void;\n    }\n    export interface WriteStream extends stream.Writable {\n        close(): void;\n        bytesWritten: number;\n    }\n\n    /**\n     * Asynchronous rename.\n     * @param oldPath\n     * @param newPath\n     * @param callback No arguments other than a possible exception are given to the completion callback.\n     */\n    export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    /**\n     * Synchronous rename\n     * @param oldPath\n     * @param newPath\n     */\n    export function renameSync(oldPath: string, newPath: string): void;\n    export function truncate(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function truncate(path: string, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function truncateSync(path: string, len?: number): void;\n    export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function ftruncateSync(fd: number, len?: number): void;\n    export function chown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function chownSync(path: string, uid: number, gid: number): void;\n    export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function fchownSync(fd: number, uid: number, gid: number): void;\n    export function lchown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function lchownSync(path: string, uid: number, gid: number): void;\n    export function chmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function chmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function chmodSync(path: string, mode: number): void;\n    export function chmodSync(path: string, mode: string): void;\n    export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function fchmodSync(fd: number, mode: number): void;\n    export function fchmodSync(fd: number, mode: string): void;\n    export function lchmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function lchmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function lchmodSync(path: string, mode: number): void;\n    export function lchmodSync(path: string, mode: string): void;\n    export function stat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void;\n    export function lstat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void;\n    export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void;\n    export function statSync(path: string): Stats;\n    export function lstatSync(path: string): Stats;\n    export function fstatSync(fd: number): Stats;\n    export function link(srcpath: string, dstpath: string, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function linkSync(srcpath: string, dstpath: string): void;\n    export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function symlinkSync(srcpath: string, dstpath: string, type?: string): void;\n    export function readlink(path: string, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void;\n    export function readlinkSync(path: string): string;\n    export function realpath(path: string, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void;\n    export function realpath(path: string, cache: {[path: string]: string}, callback: (err: NodeJS.ErrnoException, resolvedPath: string) =>any): void;\n    export function realpathSync(path: string, cache?: { [path: string]: string }): string;\n    /*\n     * Asynchronous unlink - deletes the file specified in {path}\n     *\n     * @param path\n     * @param callback No arguments other than a possible exception are given to the completion callback.\n     */\n    export function unlink(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    /*\n     * Synchronous unlink - deletes the file specified in {path}\n     *\n     * @param path\n     */\n    export function unlinkSync(path: string): void;\n    /*\n     * Asynchronous rmdir - removes the directory specified in {path}\n     *\n     * @param path\n     * @param callback No arguments other than a possible exception are given to the completion callback.\n     */\n    export function rmdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    /*\n     * Synchronous rmdir - removes the directory specified in {path}\n     *\n     * @param path\n     */\n    export function rmdirSync(path: string): void;\n    /*\n     * Asynchronous mkdir - creates the directory specified in {path}.  Parameter {mode} defaults to 0777.\n     *\n     * @param path\n     * @param callback No arguments other than a possible exception are given to the completion callback.\n     */\n    export function mkdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    /*\n     * Asynchronous mkdir - creates the directory specified in {path}.  Parameter {mode} defaults to 0777.\n     *\n     * @param path\n     * @param mode\n     * @param callback No arguments other than a possible exception are given to the completion callback.\n     */\n    export function mkdir(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    /*\n     * Asynchronous mkdir - creates the directory specified in {path}.  Parameter {mode} defaults to 0777.\n     *\n     * @param path\n     * @param mode\n     * @param callback No arguments other than a possible exception are given to the completion callback.\n     */\n    export function mkdir(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    /*\n     * Synchronous mkdir - creates the directory specified in {path}.  Parameter {mode} defaults to 0777.\n     *\n     * @param path\n     * @param mode\n     * @param callback No arguments other than a possible exception are given to the completion callback.\n     */\n    export function mkdirSync(path: string, mode?: number): void;\n    /*\n     * Synchronous mkdir - creates the directory specified in {path}.  Parameter {mode} defaults to 0777.\n     *\n     * @param path\n     * @param mode\n     * @param callback No arguments other than a possible exception are given to the completion callback.\n     */\n    export function mkdirSync(path: string, mode?: string): void;\n    export function readdir(path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void;\n    export function readdirSync(path: string): string[];\n    export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function closeSync(fd: number): void;\n    export function open(path: string, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void;\n    export function open(path: string, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void;\n    export function open(path: string, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void;\n    export function openSync(path: string, flags: string, mode?: number): number;\n    export function openSync(path: string, flags: string, mode?: string): number;\n    export function utimes(path: string, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function utimes(path: string, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function utimesSync(path: string, atime: number, mtime: number): void;\n    export function utimesSync(path: string, atime: Date, mtime: Date): void;\n    export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function futimesSync(fd: number, atime: number, mtime: number): void;\n    export function futimesSync(fd: number, atime: Date, mtime: Date): void;\n    export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function fsyncSync(fd: number): void;\n    export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void;\n    export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number;\n    export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void;\n    export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number;\n    /*\n     * Asynchronous readFile - Asynchronously reads the entire contents of a file.\n     *\n     * @param fileName\n     * @param encoding\n     * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file.\n     */\n    export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void;\n    /*\n     * Asynchronous readFile - Asynchronously reads the entire contents of a file.\n     *\n     * @param fileName\n     * @param options An object with optional {encoding} and {flag} properties.  If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer.\n     * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file.\n     */\n    export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void;\n    /*\n     * Asynchronous readFile - Asynchronously reads the entire contents of a file.\n     *\n     * @param fileName\n     * @param options An object with optional {encoding} and {flag} properties.  If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer.\n     * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file.\n     */\n    export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void;\n    /*\n     * Asynchronous readFile - Asynchronously reads the entire contents of a file.\n     *\n     * @param fileName\n     * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file.\n     */\n    export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void;\n    /*\n     * Synchronous readFile - Synchronously reads the entire contents of a file.\n     *\n     * @param fileName\n     * @param encoding\n     */\n    export function readFileSync(filename: string, encoding: string): string;\n    /*\n     * Synchronous readFile - Synchronously reads the entire contents of a file.\n     *\n     * @param fileName\n     * @param options An object with optional {encoding} and {flag} properties.  If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer.\n     */\n    export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string;\n    /*\n     * Synchronous readFile - Synchronously reads the entire contents of a file.\n     *\n     * @param fileName\n     * @param options An object with optional {encoding} and {flag} properties.  If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer.\n     */\n    export function readFileSync(filename: string, options?: { flag?: string; }): Buffer;\n    export function writeFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void;\n    export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void;\n    export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void;\n    export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void;\n    export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void;\n    export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void;\n    export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void;\n    export function appendFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void;\n    export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void;\n    export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void;\n    export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void;\n    export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void;\n    export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void;\n    export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher;\n    export function watch(filename: string, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher;\n    export function exists(path: string, callback?: (exists: boolean) => void): void;\n    export function existsSync(path: string): boolean;\n    /** Constant for fs.access(). File is visible to the calling process. */\n    export var F_OK: number;\n    /** Constant for fs.access(). File can be read by the calling process. */\n    export var R_OK: number;\n    /** Constant for fs.access(). File can be written by the calling process. */\n    export var W_OK: number;\n    /** Constant for fs.access(). File can be executed by the calling process. */\n    export var X_OK: number;\n    /** Tests a user's permissions for the file specified by path. */\n    export function access(path: string, callback: (err: NodeJS.ErrnoException) => void): void;\n    export function access(path: string, mode: number, callback: (err: NodeJS.ErrnoException) => void): void;\n    /** Synchronous version of fs.access. This throws if any accessibility checks fail, and does nothing otherwise. */\n    export function accessSync(path: string, mode ?: number): void;\n    export function createReadStream(path: string, options?: {\n        flags?: string;\n        encoding?: string;\n        fd?: string;\n        mode?: number;\n        bufferSize?: number;\n    }): ReadStream;\n    export function createReadStream(path: string, options?: {\n        flags?: string;\n        encoding?: string;\n        fd?: string;\n        mode?: string;\n        bufferSize?: number;\n    }): ReadStream;\n    export function createWriteStream(path: string, options?: {\n        flags?: string;\n        encoding?: string;\n        string?: string;\n    }): WriteStream;\n}\n\ndeclare module \"path\" {\n\n    /**\n     * A parsed path object generated by path.parse() or consumed by path.format().\n     */\n    export interface ParsedPath {\n        /**\n         * The root of the path such as '/' or 'c:\\'\n         */\n        root: string;\n        /**\n         * The full directory path such as '/home/user/dir' or 'c:\\path\\dir'\n         */\n        dir: string;\n        /**\n         * The file name including extension (if any) such as 'index.html'\n         */\n        base: string;\n        /**\n         * The file extension (if any) such as '.html'\n         */\n        ext: string;\n        /**\n         * The file name without extension (if any) such as 'index'\n         */\n        name: string;\n    }\n\n    /**\n     * Normalize a string path, reducing '..' and '.' parts.\n     * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used.\n     *\n     * @param p string path to normalize.\n     */\n    export function normalize(p: string): string;\n    /**\n     * Join all arguments together and normalize the resulting path.\n     * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.\n     *\n     * @param paths string paths to join.\n     */\n    export function join(...paths: any[]): string;\n    /**\n     * Join all arguments together and normalize the resulting path.\n     * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.\n     *\n     * @param paths string paths to join.\n     */\n    export function join(...paths: string[]): string;\n    /**\n     * The right-most parameter is considered {to}.  Other parameters are considered an array of {from}.\n     *\n     * Starting from leftmost {from} paramter, resolves {to} to an absolute path.\n     *\n     * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory.\n     *\n     * @param pathSegments string paths to join.  Non-string arguments are ignored.\n     */\n    export function resolve(...pathSegments: any[]): string;\n    /**\n     * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory.\n     *\n     * @param path path to test.\n     */\n    export function isAbsolute(path: string): boolean;\n    /**\n     * Solve the relative path from {from} to {to}.\n     * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve.\n     *\n     * @param from\n     * @param to\n     */\n    export function relative(from: string, to: string): string;\n    /**\n     * Return the directory name of a path. Similar to the Unix dirname command.\n     *\n     * @param p the path to evaluate.\n     */\n    export function dirname(p: string): string;\n    /**\n     * Return the last portion of a path. Similar to the Unix basename command.\n     * Often used to extract the file name from a fully qualified path.\n     *\n     * @param p the path to evaluate.\n     * @param ext optionally, an extension to remove from the result.\n     */\n    export function basename(p: string, ext?: string): string;\n    /**\n     * Return the extension of the path, from the last '.' to end of string in the last portion of the path.\n     * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string\n     *\n     * @param p the path to evaluate.\n     */\n    export function extname(p: string): string;\n    /**\n     * The platform-specific file separator. '\\\\' or '/'.\n     */\n    export var sep: string;\n    /**\n     * The platform-specific file delimiter. ';' or ':'.\n     */\n    export var delimiter: string;\n    /**\n     * Returns an object from a path string - the opposite of format().\n     *\n     * @param pathString path to evaluate.\n     */\n    export function parse(pathString: string): ParsedPath;\n    /**\n     * Returns a path string from an object - the opposite of parse().\n     *\n     * @param pathString path to evaluate.\n     */\n    export function format(pathObject: ParsedPath): string;\n\n    export module posix {\n      export function normalize(p: string): string;\n      export function join(...paths: any[]): string;\n      export function resolve(...pathSegments: any[]): string;\n      export function isAbsolute(p: string): boolean;\n      export function relative(from: string, to: string): string;\n      export function dirname(p: string): string;\n      export function basename(p: string, ext?: string): string;\n      export function extname(p: string): string;\n      export var sep: string;\n      export var delimiter: string;\n      export function parse(p: string): ParsedPath;\n      export function format(pP: ParsedPath): string;\n    }\n\n    export module win32 {\n      export function normalize(p: string): string;\n      export function join(...paths: any[]): string;\n      export function resolve(...pathSegments: any[]): string;\n      export function isAbsolute(p: string): boolean;\n      export function relative(from: string, to: string): string;\n      export function dirname(p: string): string;\n      export function basename(p: string, ext?: string): string;\n      export function extname(p: string): string;\n      export var sep: string;\n      export var delimiter: string;\n      export function parse(p: string): ParsedPath;\n      export function format(pP: ParsedPath): string;\n    }\n}\n\ndeclare module \"string_decoder\" {\n    export interface NodeStringDecoder {\n        write(buffer: Buffer): string;\n        detectIncompleteChar(buffer: Buffer): number;\n    }\n    export var StringDecoder: {\n        new (encoding: string): NodeStringDecoder;\n    };\n}\n\ndeclare module \"tls\" {\n    import crypto = require(\"crypto\");\n    import net = require(\"net\");\n    import stream = require(\"stream\");\n\n    var CLIENT_RENEG_LIMIT: number;\n    var CLIENT_RENEG_WINDOW: number;\n\n    export interface TlsOptions {\n        pfx?: any;   //string or buffer\n        key?: any;   //string or buffer\n        passphrase?: string;\n        cert?: any;\n        ca?: any;    //string or buffer\n        crl?: any;   //string or string array\n        ciphers?: string;\n        honorCipherOrder?: any;\n        requestCert?: boolean;\n        rejectUnauthorized?: boolean;\n        NPNProtocols?: any;  //array or Buffer;\n        SNICallback?: (servername: string) => any;\n    }\n\n    export interface ConnectionOptions {\n        host?: string;\n        port?: number;\n        socket?: net.Socket;\n        pfx?: any;   //string | Buffer\n        key?: any;   //string | Buffer\n        passphrase?: string;\n        cert?: any;  //string | Buffer\n        ca?: any;    //Array of string | Buffer\n        rejectUnauthorized?: boolean;\n        NPNProtocols?: any;  //Array of string | Buffer\n        servername?: string;\n    }\n\n    export interface Server extends net.Server {\n        // Extended base methods\n        listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server;\n        listen(path: string, listeningListener?: Function): Server;\n        listen(handle: any, listeningListener?: Function): Server;\n\n        listen(port: number, host?: string, callback?: Function): Server;\n        close(): Server;\n        address(): { port: number; family: string; address: string; };\n        addContext(hostName: string, credentials: {\n            key: string;\n            cert: string;\n            ca: string;\n        }): void;\n        maxConnections: number;\n        connections: number;\n    }\n\n    export interface ClearTextStream extends stream.Duplex {\n        authorized: boolean;\n        authorizationError: Error;\n        getPeerCertificate(): any;\n        getCipher: {\n            name: string;\n            version: string;\n        };\n        address: {\n            port: number;\n            family: string;\n            address: string;\n        };\n        remoteAddress: string;\n        remotePort: number;\n    }\n\n    export interface SecurePair {\n        encrypted: any;\n        cleartext: any;\n    }\n\n    export interface SecureContextOptions {\n        pfx?: any;   //string | buffer\n        key?: any;   //string | buffer\n        passphrase?: string;\n        cert?: any;  // string | buffer\n        ca?: any;    // string | buffer\n        crl?: any;   // string | string[]\n        ciphers?: string;\n        honorCipherOrder?: boolean;\n    }\n\n    export interface SecureContext {\n        context: any;\n    }\n\n    export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) =>void ): Server;\n    export function connect(options: TlsOptions, secureConnectionListener?: () =>void ): ClearTextStream;\n    export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream;\n    export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream;\n    export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair;\n    export function createSecureContext(details: SecureContextOptions): SecureContext;\n}\n\ndeclare module \"crypto\" {\n    export interface CredentialDetails {\n        pfx: string;\n        key: string;\n        passphrase: string;\n        cert: string;\n        ca: any;    //string | string array\n        crl: any;   //string | string array\n        ciphers: string;\n    }\n    export interface Credentials { context?: any; }\n    export function createCredentials(details: CredentialDetails): Credentials;\n    export function createHash(algorithm: string): Hash;\n    export function createHmac(algorithm: string, key: string): Hmac;\n    export function createHmac(algorithm: string, key: Buffer): Hmac;\n    interface Hash {\n        update(data: any, input_encoding?: string): Hash;\n        digest(encoding: 'buffer'): Buffer;\n        digest(encoding: string): any;\n        digest(): Buffer;\n    }\n    interface Hmac {\n        update(data: any, input_encoding?: string): Hmac;\n        digest(encoding: 'buffer'): Buffer;\n        digest(encoding: string): any;\n        digest(): Buffer;\n    }\n    export function createCipher(algorithm: string, password: any): Cipher;\n    export function createCipheriv(algorithm: string, key: any, iv: any): Cipher;\n    interface Cipher {\n        update(data: Buffer): Buffer;\n        update(data: string, input_encoding?: string, output_encoding?: string): string;\n        final(): Buffer;\n        final(output_encoding: string): string;\n        setAutoPadding(auto_padding: boolean): void;\n    }\n    export function createDecipher(algorithm: string, password: any): Decipher;\n    export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher;\n    interface Decipher {\n        update(data: Buffer): Buffer;\n        update(data: string, input_encoding?: string, output_encoding?: string): string;\n        final(): Buffer;\n        final(output_encoding: string): string;\n        setAutoPadding(auto_padding: boolean): void;\n    }\n    export function createSign(algorithm: string): Signer;\n    interface Signer {\n        update(data: any): void;\n        sign(private_key: string, output_format: string): string;\n    }\n    export function createVerify(algorith: string): Verify;\n    interface Verify {\n        update(data: any): void;\n        verify(object: string, signature: string, signature_format?: string): boolean;\n    }\n    export function createDiffieHellman(prime_length: number): DiffieHellman;\n    export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman;\n    interface DiffieHellman {\n        generateKeys(encoding?: string): string;\n        computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string;\n        getPrime(encoding?: string): string;\n        getGenerator(encoding: string): string;\n        getPublicKey(encoding?: string): string;\n        getPrivateKey(encoding?: string): string;\n        setPublicKey(public_key: string, encoding?: string): void;\n        setPrivateKey(public_key: string, encoding?: string): void;\n    }\n    export function getDiffieHellman(group_name: string): DiffieHellman;\n    export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void;\n    export function pbkdf2Sync(password: string, salt: string, iterations: number, keylen: number) : Buffer;\n    export function randomBytes(size: number): Buffer;\n    export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void;\n    export function pseudoRandomBytes(size: number): Buffer;\n    export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void;\n}\n\ndeclare module \"stream\" {\n    import events = require(\"events\");\n\n    export interface Stream extends events.EventEmitter {\n        pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T;\n    }\n\n    export interface ReadableOptions {\n        highWaterMark?: number;\n        encoding?: string;\n        objectMode?: boolean;\n    }\n\n    export class Readable extends events.EventEmitter implements NodeJS.ReadableStream {\n        readable: boolean;\n        constructor(opts?: ReadableOptions);\n        _read(size: number): void;\n        read(size?: number): string|Buffer;\n        setEncoding(encoding: string): void;\n        pause(): void;\n        resume(): void;\n        pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T;\n        unpipe<T extends NodeJS.WritableStream>(destination?: T): void;\n        unshift(chunk: string): void;\n        unshift(chunk: Buffer): void;\n        wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream;\n        push(chunk: any, encoding?: string): boolean;\n    }\n\n    export interface WritableOptions {\n        highWaterMark?: number;\n        decodeStrings?: boolean;\n    }\n\n    export class Writable extends events.EventEmitter implements NodeJS.WritableStream {\n        writable: boolean;\n        constructor(opts?: WritableOptions);\n        _write(data: Buffer, encoding: string, callback: Function): void;\n        _write(data: string, encoding: string, callback: Function): void;\n        write(buffer: Buffer, cb?: Function): boolean;\n        write(str: string, cb?: Function): boolean;\n        write(str: string, encoding?: string, cb?: Function): boolean;\n        end(): void;\n        end(buffer: Buffer, cb?: Function): void;\n        end(str: string, cb?: Function): void;\n        end(str: string, encoding?: string, cb?: Function): void;\n    }\n\n    export interface DuplexOptions extends ReadableOptions, WritableOptions {\n        allowHalfOpen?: boolean;\n    }\n\n    // Note: Duplex extends both Readable and Writable.\n    export class Duplex extends Readable implements NodeJS.ReadWriteStream {\n        writable: boolean;\n        constructor(opts?: DuplexOptions);\n        _write(data: Buffer, encoding: string, callback: Function): void;\n        _write(data: string, encoding: string, callback: Function): void;\n        write(buffer: Buffer, cb?: Function): boolean;\n        write(str: string, cb?: Function): boolean;\n        write(str: string, encoding?: string, cb?: Function): boolean;\n        end(): void;\n        end(buffer: Buffer, cb?: Function): void;\n        end(str: string, cb?: Function): void;\n        end(str: string, encoding?: string, cb?: Function): void;\n    }\n\n    export interface TransformOptions extends ReadableOptions, WritableOptions {}\n\n    // Note: Transform lacks the _read and _write methods of Readable/Writable.\n    export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream {\n        readable: boolean;\n        writable: boolean;\n        constructor(opts?: TransformOptions);\n        _transform(chunk: Buffer, encoding: string, callback: Function): void;\n        _transform(chunk: string, encoding: string, callback: Function): void;\n        _flush(callback: Function): void;\n        read(size?: number): any;\n        setEncoding(encoding: string): void;\n        pause(): void;\n        resume(): void;\n        pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T;\n        unpipe<T extends NodeJS.WritableStream>(destination?: T): void;\n        unshift(chunk: string): void;\n        unshift(chunk: Buffer): void;\n        wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream;\n        push(chunk: any, encoding?: string): boolean;\n        write(buffer: Buffer, cb?: Function): boolean;\n        write(str: string, cb?: Function): boolean;\n        write(str: string, encoding?: string, cb?: Function): boolean;\n        end(): void;\n        end(buffer: Buffer, cb?: Function): void;\n        end(str: string, cb?: Function): void;\n        end(str: string, encoding?: string, cb?: Function): void;\n    }\n\n    export class PassThrough extends Transform {}\n}\n\ndeclare module \"util\" {\n    export interface InspectOptions {\n        showHidden?: boolean;\n        depth?: number;\n        colors?: boolean;\n        customInspect?: boolean;\n    }\n\n    export function format(format: any, ...param: any[]): string;\n    export function debug(string: string): void;\n    export function error(...param: any[]): void;\n    export function puts(...param: any[]): void;\n    export function print(...param: any[]): void;\n    export function log(string: string): void;\n    export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string;\n    export function inspect(object: any, options: InspectOptions): string;\n    export function isArray(object: any): boolean;\n    export function isRegExp(object: any): boolean;\n    export function isDate(object: any): boolean;\n    export function isError(object: any): boolean;\n    export function inherits(constructor: any, superConstructor: any): void;\n}\n\ndeclare module \"assert\" {\n    function internal (value: any, message?: string): void;\n    module internal {\n        export class AssertionError implements Error {\n            name: string;\n            message: string;\n            actual: any;\n            expected: any;\n            operator: string;\n            generatedMessage: boolean;\n\n            constructor(options?: {message?: string; actual?: any; expected?: any;\n                                  operator?: string; stackStartFunction?: Function});\n        }\n\n        export function fail(actual?: any, expected?: any, message?: string, operator?: string): void;\n        export function ok(value: any, message?: string): void;\n        export function equal(actual: any, expected: any, message?: string): void;\n        export function notEqual(actual: any, expected: any, message?: string): void;\n        export function deepEqual(actual: any, expected: any, message?: string): void;\n        export function notDeepEqual(acutal: any, expected: any, message?: string): void;\n        export function strictEqual(actual: any, expected: any, message?: string): void;\n        export function notStrictEqual(actual: any, expected: any, message?: string): void;\n        export var throws: {\n            (block: Function, message?: string): void;\n            (block: Function, error: Function, message?: string): void;\n            (block: Function, error: RegExp, message?: string): void;\n            (block: Function, error: (err: any) => boolean, message?: string): void;\n        };\n\n        export var doesNotThrow: {\n            (block: Function, message?: string): void;\n            (block: Function, error: Function, message?: string): void;\n            (block: Function, error: RegExp, message?: string): void;\n            (block: Function, error: (err: any) => boolean, message?: string): void;\n        };\n\n        export function ifError(value: any): void;\n    }\n\n    export = internal;\n}\n\ndeclare module \"tty\" {\n    import net = require(\"net\");\n\n    export function isatty(fd: number): boolean;\n    export interface ReadStream extends net.Socket {\n        isRaw: boolean;\n        setRawMode(mode: boolean): void;\n    }\n    export interface WriteStream extends net.Socket {\n        columns: number;\n        rows: number;\n    }\n}\n\ndeclare module \"domain\" {\n    import events = require(\"events\");\n\n    export class Domain extends events.EventEmitter {\n        run(fn: Function): void;\n        add(emitter: events.EventEmitter): void;\n        remove(emitter: events.EventEmitter): void;\n        bind(cb: (err: Error, data: any) => any): any;\n        intercept(cb: (data: any) => any): any;\n        dispose(): void;\n\n        addListener(event: string, listener: Function): Domain;\n        on(event: string, listener: Function): Domain;\n        once(event: string, listener: Function): Domain;\n        removeListener(event: string, listener: Function): Domain;\n        removeAllListeners(event?: string): Domain;\n    }\n\n    export function create(): Domain;\n}\n\ndeclare module \"constants\" {\n    export var E2BIG: number;\n    export var EACCES: number;\n    export var EADDRINUSE: number;\n    export var EADDRNOTAVAIL: number;\n    export var EAFNOSUPPORT: number;\n    export var EAGAIN: number;\n    export var EALREADY: number;\n    export var EBADF: number;\n    export var EBADMSG: number;\n    export var EBUSY: number;\n    export var ECANCELED: number;\n    export var ECHILD: number;\n    export var ECONNABORTED: number;\n    export var ECONNREFUSED: number;\n    export var ECONNRESET: number;\n    export var EDEADLK: number;\n    export var EDESTADDRREQ: number;\n    export var EDOM: number;\n    export var EEXIST: number;\n    export var EFAULT: number;\n    export var EFBIG: number;\n    export var EHOSTUNREACH: number;\n    export var EIDRM: number;\n    export var EILSEQ: number;\n    export var EINPROGRESS: number;\n    export var EINTR: number;\n    export var EINVAL: number;\n    export var EIO: number;\n    export var EISCONN: number;\n    export var EISDIR: number;\n    export var ELOOP: number;\n    export var EMFILE: number;\n    export var EMLINK: number;\n    export var EMSGSIZE: number;\n    export var ENAMETOOLONG: number;\n    export var ENETDOWN: number;\n    export var ENETRESET: number;\n    export var ENETUNREACH: number;\n    export var ENFILE: number;\n    export var ENOBUFS: number;\n    export var ENODATA: number;\n    export var ENODEV: number;\n    export var ENOENT: number;\n    export var ENOEXEC: number;\n    export var ENOLCK: number;\n    export var ENOLINK: number;\n    export var ENOMEM: number;\n    export var ENOMSG: number;\n    export var ENOPROTOOPT: number;\n    export var ENOSPC: number;\n    export var ENOSR: number;\n    export var ENOSTR: number;\n    export var ENOSYS: number;\n    export var ENOTCONN: number;\n    export var ENOTDIR: number;\n    export var ENOTEMPTY: number;\n    export var ENOTSOCK: number;\n    export var ENOTSUP: number;\n    export var ENOTTY: number;\n    export var ENXIO: number;\n    export var EOPNOTSUPP: number;\n    export var EOVERFLOW: number;\n    export var EPERM: number;\n    export var EPIPE: number;\n    export var EPROTO: number;\n    export var EPROTONOSUPPORT: number;\n    export var EPROTOTYPE: number;\n    export var ERANGE: number;\n    export var EROFS: number;\n    export var ESPIPE: number;\n    export var ESRCH: number;\n    export var ETIME: number;\n    export var ETIMEDOUT: number;\n    export var ETXTBSY: number;\n    export var EWOULDBLOCK: number;\n    export var EXDEV: number;\n    export var WSAEINTR: number;\n    export var WSAEBADF: number;\n    export var WSAEACCES: number;\n    export var WSAEFAULT: number;\n    export var WSAEINVAL: number;\n    export var WSAEMFILE: number;\n    export var WSAEWOULDBLOCK: number;\n    export var WSAEINPROGRESS: number;\n    export var WSAEALREADY: number;\n    export var WSAENOTSOCK: number;\n    export var WSAEDESTADDRREQ: number;\n    export var WSAEMSGSIZE: number;\n    export var WSAEPROTOTYPE: number;\n    export var WSAENOPROTOOPT: number;\n    export var WSAEPROTONOSUPPORT: number;\n    export var WSAESOCKTNOSUPPORT: number;\n    export var WSAEOPNOTSUPP: number;\n    export var WSAEPFNOSUPPORT: number;\n    export var WSAEAFNOSUPPORT: number;\n    export var WSAEADDRINUSE: number;\n    export var WSAEADDRNOTAVAIL: number;\n    export var WSAENETDOWN: number;\n    export var WSAENETUNREACH: number;\n    export var WSAENETRESET: number;\n    export var WSAECONNABORTED: number;\n    export var WSAECONNRESET: number;\n    export var WSAENOBUFS: number;\n    export var WSAEISCONN: number;\n    export var WSAENOTCONN: number;\n    export var WSAESHUTDOWN: number;\n    export var WSAETOOMANYREFS: number;\n    export var WSAETIMEDOUT: number;\n    export var WSAECONNREFUSED: number;\n    export var WSAELOOP: number;\n    export var WSAENAMETOOLONG: number;\n    export var WSAEHOSTDOWN: number;\n    export var WSAEHOSTUNREACH: number;\n    export var WSAENOTEMPTY: number;\n    export var WSAEPROCLIM: number;\n    export var WSAEUSERS: number;\n    export var WSAEDQUOT: number;\n    export var WSAESTALE: number;\n    export var WSAEREMOTE: number;\n    export var WSASYSNOTREADY: number;\n    export var WSAVERNOTSUPPORTED: number;\n    export var WSANOTINITIALISED: number;\n    export var WSAEDISCON: number;\n    export var WSAENOMORE: number;\n    export var WSAECANCELLED: number;\n    export var WSAEINVALIDPROCTABLE: number;\n    export var WSAEINVALIDPROVIDER: number;\n    export var WSAEPROVIDERFAILEDINIT: number;\n    export var WSASYSCALLFAILURE: number;\n    export var WSASERVICE_NOT_FOUND: number;\n    export var WSATYPE_NOT_FOUND: number;\n    export var WSA_E_NO_MORE: number;\n    export var WSA_E_CANCELLED: number;\n    export var WSAEREFUSED: number;\n    export var SIGHUP: number;\n    export var SIGINT: number;\n    export var SIGILL: number;\n    export var SIGABRT: number;\n    export var SIGFPE: number;\n    export var SIGKILL: number;\n    export var SIGSEGV: number;\n    export var SIGTERM: number;\n    export var SIGBREAK: number;\n    export var SIGWINCH: number;\n    export var SSL_OP_ALL: number;\n    export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number;\n    export var SSL_OP_CIPHER_SERVER_PREFERENCE: number;\n    export var SSL_OP_CISCO_ANYCONNECT: number;\n    export var SSL_OP_COOKIE_EXCHANGE: number;\n    export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number;\n    export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number;\n    export var SSL_OP_EPHEMERAL_RSA: number;\n    export var SSL_OP_LEGACY_SERVER_CONNECT: number;\n    export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number;\n    export var SSL_OP_MICROSOFT_SESS_ID_BUG: number;\n    export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number;\n    export var SSL_OP_NETSCAPE_CA_DN_BUG: number;\n    export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number;\n    export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number;\n    export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number;\n    export var SSL_OP_NO_COMPRESSION: number;\n    export var SSL_OP_NO_QUERY_MTU: number;\n    export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number;\n    export var SSL_OP_NO_SSLv2: number;\n    export var SSL_OP_NO_SSLv3: number;\n    export var SSL_OP_NO_TICKET: number;\n    export var SSL_OP_NO_TLSv1: number;\n    export var SSL_OP_NO_TLSv1_1: number;\n    export var SSL_OP_NO_TLSv1_2: number;\n    export var SSL_OP_PKCS1_CHECK_1: number;\n    export var SSL_OP_PKCS1_CHECK_2: number;\n    export var SSL_OP_SINGLE_DH_USE: number;\n    export var SSL_OP_SINGLE_ECDH_USE: number;\n    export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number;\n    export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number;\n    export var SSL_OP_TLS_BLOCK_PADDING_BUG: number;\n    export var SSL_OP_TLS_D5_BUG: number;\n    export var SSL_OP_TLS_ROLLBACK_BUG: number;\n    export var ENGINE_METHOD_DSA: number;\n    export var ENGINE_METHOD_DH: number;\n    export var ENGINE_METHOD_RAND: number;\n    export var ENGINE_METHOD_ECDH: number;\n    export var ENGINE_METHOD_ECDSA: number;\n    export var ENGINE_METHOD_CIPHERS: number;\n    export var ENGINE_METHOD_DIGESTS: number;\n    export var ENGINE_METHOD_STORE: number;\n    export var ENGINE_METHOD_PKEY_METHS: number;\n    export var ENGINE_METHOD_PKEY_ASN1_METHS: number;\n    export var ENGINE_METHOD_ALL: number;\n    export var ENGINE_METHOD_NONE: number;\n    export var DH_CHECK_P_NOT_SAFE_PRIME: number;\n    export var DH_CHECK_P_NOT_PRIME: number;\n    export var DH_UNABLE_TO_CHECK_GENERATOR: number;\n    export var DH_NOT_SUITABLE_GENERATOR: number;\n    export var NPN_ENABLED: number;\n    export var RSA_PKCS1_PADDING: number;\n    export var RSA_SSLV23_PADDING: number;\n    export var RSA_NO_PADDING: number;\n    export var RSA_PKCS1_OAEP_PADDING: number;\n    export var RSA_X931_PADDING: number;\n    export var RSA_PKCS1_PSS_PADDING: number;\n    export var POINT_CONVERSION_COMPRESSED: number;\n    export var POINT_CONVERSION_UNCOMPRESSED: number;\n    export var POINT_CONVERSION_HYBRID: number;\n    export var O_RDONLY: number;\n    export var O_WRONLY: number;\n    export var O_RDWR: number;\n    export var S_IFMT: number;\n    export var S_IFREG: number;\n    export var S_IFDIR: number;\n    export var S_IFCHR: number;\n    export var S_IFLNK: number;\n    export var O_CREAT: number;\n    export var O_EXCL: number;\n    export var O_TRUNC: number;\n    export var O_APPEND: number;\n    export var F_OK: number;\n    export var R_OK: number;\n    export var W_OK: number;\n    export var X_OK: number;\n    export var UV_UDP_REUSEADDR: number;\n}\n"
  },
  {
    "path": "code/compiler/typings/tsd.d.ts",
    "content": "/// <reference path=\"node/node.d.ts\" />\n"
  },
  {
    "path": "code/declarationspaces/declarationspace.js",
    "content": "var first;\n(function (first) {\n    var Foo = (function () {\n        function Foo() {\n        }\n        return Foo;\n    })();\n    var foo;\n    var bar;\n    var bas;\n})(first = exports.first || (exports.first = {}));\nvar second;\n(function (second) {\n    ;\n    var bar = Bar;\n})(second || (second = {}));\nvar third;\n(function (third) {\n    var Foo = (function () {\n        function Foo() {\n        }\n        return Foo;\n    })();\n    var someVar = Foo;\n    var someOtherVar = 123;\n})(third || (third = {}));\nvar fourn;\n(function (fourn) {\n    var foo = 123;\n    var bar;\n})(fourn || (fourn = {}));\nvar meh;\n(function (meh) {\n    var something = {};\n})(meh || (meh = {}));\nvar utility;\n(function (utility) {\n    function log(msg) {\n        console.log(msg);\n    }\n    utility.log = log;\n    function error(msg) {\n        console.error(msg);\n    }\n    utility.error = error;\n})(utility || (utility = {}));\nutility.log('Call me');\nutility.error('maybe!');\nvar importing;\n(function (importing) {\n    var Foo = (function () {\n        function Foo() {\n        }\n        return Foo;\n    })();\n    var Bar = Foo;\n    var bar;\n})(importing || (importing = {}));\nvar importing;\n(function (importing) {\n    var Foo = (function () {\n        function Foo() {\n        }\n        return Foo;\n    })();\n    importing.Foo = Foo;\n})(importing || (importing = {}));\nvar Bar = importing.Foo;\nvar bar;\nvar typeofAnnotation;\n(function (typeofAnnotation) {\n    var foo = 123;\n    var bar;\n    bar = 456;\n    bar = '789';\n})(typeofAnnotation || (typeofAnnotation = {}));\n"
  },
  {
    "path": "code/declarationspaces/declarationspace.ts",
    "content": "export module first {\n    class Foo { }\n    interface Bar { }\n    type Bas = {}\n\n    var foo: Foo;\n    var bar: Bar;\n    var bas: Bas;\n}\n\nnamespace second {\n    interface Bar { };\n    var bar = Bar; // ERROR: \"cannot find name 'Bar'\"\n}\n\nnamespace third {\n    class Foo { }\n    var someVar = Foo;\n    var someOtherVar = 123;\n}\n\nnamespace fourn {\n    var foo = 123;\n    var bar: foo; // ERROR: \"cannot find name 'foo'\"\n}\n\n\nnamespace meh {\n    var something = {};\n    // (function(something) {\n    //     something.foo = 123;\n    // })(something || something = {})\n}\n\nnamespace utility {\n    export function log(msg) {\n        console.log(msg);\n    }\n    export function error(msg) {\n        console.error(msg);\n    }\n}\n\n// usage\nutility.log('Call me');\nutility.error('maybe!');\n\n\nmodule importing {\n    class Foo { }\n    var Bar = Foo;\n    var bar: Bar; // ERROR: \"cannot find name 'Bar'\"\n}\n\nnamespace importing {\n    export class Foo { }\n}\n\nimport Bar = importing.Foo;\nvar bar: Bar; // Okay\n\nnamespace typeofAnnotation {\n    var foo = 123;\n    var bar: typeof foo; // `bar` has the same type as `foo` (here `number`)\n    bar = 456; // Okay\n    bar = '789'; // ERROR: Type `string` is not `assignable` to type `number`\n}"
  },
  {
    "path": "code/dynamic-import-expressions/dynamicImportExpression.js",
    "content": "\"use strict\";\nfunction myApp() {\n    import(/* webpackChunkName: \"momentjs\" */ \"moment\")\n        .then(function (moment) {\n        // lazyModule has all of the proper types, autocomplete works,\n        // type checking works, code references work \\o/\n        var time = moment().format();\n        console.log(\"TypeScript >= 2.4.0 Dynamic Import Expression:\");\n        console.log(time);\n    })\n        .catch(function (err) {\n        console.log(\"Failed to load moment\", err);\n    });\n}\n"
  },
  {
    "path": "code/dynamic-import-expressions/dynamicImportExpression.ts",
    "content": "\nfunction myApp() {\n    import(/* webpackChunkName: \"momentjs\" */ \"moment\")\n        .then((moment) => {\n            // lazyModule has all of the proper types, autocomplete works,\n            // type checking works, code references work \\o/\n            const time = moment().format();\n            console.log(\"TypeScript >= 2.4.0 Dynamic Import Expression:\");\n            console.log(time);\n        })\n        .catch((err) => {\n            console.log(\"Failed to load moment\", err);\n        });\n}\n"
  },
  {
    "path": "code/dynamic-import-expressions/package.json",
    "content": "{\n  \"name\": \"dynamic-import-expressions\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"dynamicImportExpression.js\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n  },\n  \"author\": \"Jose Quinto Zamora - https://blog.josequinto.com\",\n  \"license\": \"ISC\",\n  \"devDependencies\": {\n    \"typescript\": \"^2.4.1\"\n  },\n  \"dependencies\": {\n    \"moment\": \"^2.18.1\"\n  }\n}\n"
  },
  {
    "path": "code/dynamic-import-expressions/tsconfig.json",
    "content": "{\n    \"compilerOptions\": {\n        \"target\": \"es5\",                          \n        \"module\": \"esnext\",                     \n        \"lib\": [\n            \"dom\",\n            \"es5\",\n            \"scripthost\",\n            \"es2015.promise\"\n        ],                                        \n        \"strict\": true,                           \n        \"moduleResolution\": \"node\"            \n    },\n    \"files\": [\n      \"./dynamicImportExpression.ts\"\n  ]\n}"
  },
  {
    "path": "code/errors/common-errors.ts",
    "content": "ga();\n\nimport {debounce} from \"underscore\";\n"
  },
  {
    "path": "code/errors/interpreting-errors.ts",
    "content": "export const module = 123;\n\ntype SomethingComplex = {\n  foo: number,\n  bar: string\n}\nfunction takeSomethingComplex(arg: SomethingComplex) {\n}\nfunction getBar(): string {\n  return 'some bar';\n}\n\n//////////////////////////////////\n// Example error production\n//////////////////////////////////\nconst fail = {\n  foo: 123,\n  bar: getBar\n};\n\ntakeSomethingComplex(fail); // TS ERROR HAPPENS HERE \n"
  },
  {
    "path": "code/errors/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "code/es6/classes/abstract.js",
    "content": "exports.foo = 123;\nvar Restable = (function () {\n    function Restable() {\n        this.abstract = toJSON();\n    }\n    return Restable;\n})();\n"
  },
  {
    "path": "code/es6/classes/abstract.ts",
    "content": "export var foo = 123;\n\nclass Restable {\n    abstract toJSON() : any;\n}\n\n"
  },
  {
    "path": "code/es6/classes/class.js",
    "content": "var __extends = this.__extends || function (d, b) {\n    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n    function __() { this.constructor = d; }\n    __.prototype = b.prototype;\n    d.prototype = new __();\n};\nvar Point = (function () {\n    function Point(x, y) {\n        this.x = x;\n        this.y = y;\n    }\n    Point.prototype.add = function (point) {\n        return new Point(this.x + point.x, this.y + point.y);\n    };\n    return Point;\n})();\nvar p1 = new Point(0, 10);\nvar p2 = new Point(10, 20);\nvar p3 = p1.add(p2);\nvar Point3D = (function (_super) {\n    __extends(Point3D, _super);\n    function Point3D(x, y, z) {\n        _super.call(this, x, y);\n        this.z = z;\n    }\n    Point3D.prototype.add = function (point) {\n        var point2D = _super.prototype.add.call(this, point);\n        return new Point3D(point2D.x, point2D.y, this.z + point.z);\n    };\n    return Point3D;\n})(Point);\nvar Something = (function () {\n    function Something() {\n        Something.instances++;\n    }\n    Something.instances = 0;\n    return Something;\n})();\nvar s1 = new Something();\nvar s2 = new Something();\nconsole.log(Something.instances);\n"
  },
  {
    "path": "code/es6/classes/class.ts",
    "content": "class Point {\n    x: number;\n    y: number;\n    constructor(x: number, y: number) {\n        this.x = x;\n        this.y = y;\n    }\n    add(point: Point) {\n        return new Point(this.x + point.x, this.y + point.y);\n    }\n}\n\nvar p1 = new Point(0, 10);\nvar p2 = new Point(10, 20);\nvar p3 = p1.add(p2); // {x:10,y:30}\n\nclass Point3D extends Point {\n    z: number;\n    constructor(x: number, y: number, z: number) {\n        super(x, y);\n        this.z = z;\n    }\n    add(point: Point3D) {\n        var point2D = super.add(point);\n        return new Point3D(point2D.x, point2D.y, this.z + point.z);\n    }\n}\n\nclass Something {\n    static instances = 0;\n    constructor() {\n        Something.instances++;\n    }\n}\n\nvar s1 = new Something();\nvar s2 = new Something();\nconsole.log(Something.instances); // 2\n"
  },
  {
    "path": "code/es6/classes/super.js",
    "content": "var __extends = (this && this.__extends) || function (d, b) {\n    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n    function __() { this.constructor = d; }\n    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};\nexports.foo = 123;\nvar asdf;\n(function (asdf) {\n    var Base = (function () {\n        function Base() {\n        }\n        Base.prototype.log = function () { console.log('hello world'); };\n        return Base;\n    })();\n    var Child = (function (_super) {\n        __extends(Child, _super);\n        function Child() {\n            _super.apply(this, arguments);\n        }\n        Child.prototype.logWorld = function () { _super.prototype.log.call(this); };\n        ;\n        return Child;\n    })(Base);\n})(asdf || (asdf = {}));\nvar bse;\n(function (bse) {\n    var Base = (function () {\n        function Base() {\n            this.log = function () { console.log('hello world'); };\n        }\n        return Base;\n    })();\n    var Child = (function (_super) {\n        __extends(Child, _super);\n        function Child() {\n            _super.apply(this, arguments);\n        }\n        Child.prototype.logWorld = function () { this.log(); };\n        ;\n        return Child;\n    })(Base);\n})(bse || (bse = {}));\nvar quz;\n(function (quz) {\n    var Base = (function () {\n        function Base() {\n            this.log = function () { console.log('hello world'); };\n        }\n        return Base;\n    })();\n    var Child = (function (_super) {\n        __extends(Child, _super);\n        function Child() {\n            _super.apply(this, arguments);\n        }\n        Child.prototype.logWorld = function () { _super.prototype.log.call(this); };\n        ;\n        return Child;\n    })(Base);\n})(quz || (quz = {}));\n"
  },
  {
    "path": "code/es6/classes/super.ts",
    "content": "export var foo = 123;\n\nmodule asdf {\n    class Base {\n        log() { console.log('hello world'); }\n    }\n\n    class Child extends Base {\n        logWorld() { super.log() };\n    }\n}\n\nmodule bse {\n    class Base {\n        log = () => { console.log('hello world'); }\n    }\n\n    class Child extends Base {\n        logWorld() { this.log() };\n    }\n}\n\nmodule quz {\n    class Base {\n        log = () => { console.log('hello world'); }\n    }\n\n    class Child extends Base {\n        logWorld() { super.log() }; // ERROR : only `public` and `protected` methods of base class are accessible via `super`\n    }\n}"
  },
  {
    "path": "code/es6/classes/tsconfig.json",
    "content": "{\n    \"version\": \"1.4.1\",\n    \"compilerOptions\": {\n        \"target\": \"es5\",\n        \"module\": \"commonjs\",\n        \"declaration\": false,\n        \"noImplicitAny\": false,\n        \"removeComments\": true,\n        \"noLib\": false\n    },\n    \"filesGlob\": [\n        \"./**/*.ts\",\n        \"!./node_modules/**/*.ts\"\n    ],\n    \"files\": [\n        \"./abstract.ts\",\n        \"./class.ts\",\n        \"./super.ts\"\n    ]\n}\n"
  },
  {
    "path": "code/es6/const.js",
    "content": "exports.asdfasdfasfadf = 123;\nvar mustbeinit;\n(function (mustbeinit) {\n    var foo;\n})(mustbeinit || (mustbeinit = {}));\nvar cantbechanged;\n(function (cantbechanged) {\n    var foo = 123;\n    foo = 456;\n})(cantbechanged || (cantbechanged = {}));\nvar block;\n(function (block) {\n    var foo = 123;\n    if (true) {\n        var foo_1 = 456;\n    }\n})(block || (block = {}));\nvar protectvariablereference;\n(function (protectvariablereference) {\n    var foo = { bar: 123 };\n    foo = { bar: 456 };\n})(protectvariablereference || (protectvariablereference = {}));\nvar noProtectDeep;\n(function (noProtectDeep) {\n    var foo = { bar: 123 };\n    foo.bar = 456;\n})(noProtectDeep || (noProtectDeep = {}));\n"
  },
  {
    "path": "code/es6/const.ts",
    "content": "export var asdfasdfasfadf = 123;\n\n\nnamespace mustbeinit {\n    const foo;\n}\n\nnamespace cantbechanged {\n    const foo = 123;\n    foo = 456;\n}\n\n\nnamespace block {\n    const foo = 123;\n    if (true) {\n        const foo = 456; // Allowed as its a new variable limited to this `if` block\n    }\n}\n\n\nnamespace protectvariablereference {\n    const foo = { bar: 123 };\n    foo = { bar: 456 }; // ERROR : Left hand side of an assignment expression cannot be a constant\n}\n\n\nnamespace noProtectDeep {\n    const foo = { bar: 123 };\n    foo.bar = 456; // Allowed!\n}\n"
  },
  {
    "path": "code/es6/destructuring.js",
    "content": "exports.destructuring = true;\nvar m1;\n(function (m1) {\n    var x = 1, y = 2;\n    _a = [\n        y,\n        x\n    ], x = _a[0], y = _a[1];\n    console.log(x, y);\n    var _a;\n})(m1 || (m1 = {}));\nvar m2;\n(function (m2) {\n    var rect = {\n        x: 0,\n        y: 10,\n        width: 15,\n        height: 20\n    };\n    var x = rect.x, y = rect.y, width = rect.width, height = rect.height;\n    console.log(x, y, width, height);\n})(m2 || (m2 = {}));\nvar m3;\n(function (m3) {\n    var _a = [\n        1,\n        2,\n        3,\n        4\n    ], x = _a[0], y = _a[1], remaining = _a.slice(2);\n    console.log(x, y, remaining);\n})(m3 || (m3 = {}));\nvar m3;\n(function (m3) {\n    var _a = [\n        1,\n        2,\n        3,\n        4\n    ], x = _a[0], remaining = _a.slice(2);\n    console.log(x, remaining);\n})(m3 || (m3 = {}));\n"
  },
  {
    "path": "code/es6/destructuring.ts",
    "content": "export var destructuring = true;\n\n\nmodule m1 {\n    var x = 1, y = 2;\n    [x, y] = [y, x];\n    console.log(x, y); // 1,2\n}\n\nmodule m2 {\n    var rect = { x: 0, y: 10, width: 15, height: 20 };\n    var {x, y, width, height} = rect;\n    console.log(x, y, width, height); // 0,10,15,20\n}\n\nmodule m3 {\n    var [x, y, ...remaining] = [1, 2, 3, 4];\n    console.log(x, y, remaining); // 1, 2, [3,4]\n}\n\nmodule m3 {\n    var [x, , ...remaining] = [1, 2, 3, 4];\n    console.log(x, remaining); // 1, [3,4]\n}\n"
  },
  {
    "path": "code/es6/enums.js",
    "content": "\"use strict\";\nexports.foo = 123;\nvar Color;\n(function (Color) {\n    Color[Color[\"Red\"] = 0] = \"Red\";\n    Color[Color[\"Green\"] = 1] = \"Green\";\n    Color[Color[\"Blue\"] = 2] = \"Blue\";\n})(Color || (Color = {}));\nvar Color;\n(function (Color) {\n    Color[Color[\"DarkRed\"] = 3] = \"DarkRed\";\n    Color[Color[\"DarkGreen\"] = 4] = \"DarkGreen\";\n    Color[Color[\"DarkBlue\"] = 5] = \"DarkBlue\";\n})(Color || (Color = {}));\nvar col = Color.Red;\ncol = 0;\nvar Tristate;\n(function (Tristate) {\n    Tristate[Tristate[\"False\"] = 0] = \"False\";\n    Tristate[Tristate[\"True\"] = 1] = \"True\";\n    Tristate[Tristate[\"Unknown\"] = 2] = \"Unknown\";\n})(Tristate || (Tristate = {}));\nvar lie = Tristate.False;\nvar AnimalFlags;\n(function (AnimalFlags) {\n    AnimalFlags[AnimalFlags[\"None\"] = 0] = \"None\";\n    AnimalFlags[AnimalFlags[\"HasClaws\"] = 1] = \"HasClaws\";\n    AnimalFlags[AnimalFlags[\"CanFly\"] = 2] = \"CanFly\";\n})(AnimalFlags || (AnimalFlags = {}));\nfunction printAnimalAbilities(animal) {\n    var animalFlags = animal.flags;\n    if (animalFlags & AnimalFlags.HasClaws) {\n        console.log('animal has claws');\n    }\n    if (animalFlags & AnimalFlags.CanFly) {\n        console.log('animal can fly');\n    }\n    if (animalFlags == AnimalFlags.None) {\n        console.log('nothing');\n    }\n}\nvar animal = { flags: AnimalFlags.None };\nprintAnimalAbilities(animal);\nanimal.flags |= AnimalFlags.HasClaws;\nprintAnimalAbilities(animal);\nanimal.flags &= ~AnimalFlags.HasClaws;\nprintAnimalAbilities(animal);\nanimal.flags |= AnimalFlags.HasClaws | AnimalFlags.CanFly;\nprintAnimalAbilities(animal);\nvar EnumsWithStatics;\n(function (EnumsWithStatics) {\n    var Weekday;\n    (function (Weekday) {\n        Weekday[Weekday[\"Monday\"] = 0] = \"Monday\";\n        Weekday[Weekday[\"Tuesday\"] = 1] = \"Tuesday\";\n        Weekday[Weekday[\"Wednesday\"] = 2] = \"Wednesday\";\n        Weekday[Weekday[\"Thursday\"] = 3] = \"Thursday\";\n        Weekday[Weekday[\"Friday\"] = 4] = \"Friday\";\n        Weekday[Weekday[\"Saturday\"] = 5] = \"Saturday\";\n        Weekday[Weekday[\"Sunday\"] = 6] = \"Sunday\";\n    })(Weekday || (Weekday = {}));\n    var Weekday;\n    (function (Weekday) {\n        function isBusinessDay(day) {\n            switch (day) {\n                case Weekday.Saturday:\n                case Weekday.Sunday:\n                    return false;\n                default:\n                    return true;\n            }\n        }\n        Weekday.isBusinessDay = isBusinessDay;\n    })(Weekday || (Weekday = {}));\n    var mon = Weekday.Monday;\n    var sun = Weekday.Sunday;\n    console.log(Weekday.isBusinessDay(mon));\n    console.log(Weekday.isBusinessDay(sun));\n})(EnumsWithStatics || (EnumsWithStatics = {}));\n"
  },
  {
    "path": "code/es6/enums.ts",
    "content": "export const foo = 123;\n\nenum Color {\n    Red,\n    Green,\n    Blue\n}\n\nenum Color {\n    DarkRed = 3,\n    DarkGreen,\n    DarkBlue\n}\n\nvar col = Color.Red;\ncol = 0; // Effectively same as Color.Red\n\n\nenum Tristate {\n    False,\n    True,\n    Unknown\n}\n\nvar lie = Tristate.False;\n\n/*enum AnimalFlags {\n    None           = 0,\n    HasClaws       = 1 << 0,\n    CanFly         = 1 << 1,\n    EatsFish       = 1 << 2,\n    Endangered     = 1 << 3\n}*/\n\nenum AnimalFlags {\n    None           = 0,\n    HasClaws       = 1 << 0,\n    CanFly         = 1 << 1,\n}\n\nfunction printAnimalAbilities(animal) {\n    var animalFlags = animal.flags;\n    if (animalFlags & AnimalFlags.HasClaws) {\n        console.log('animal has claws');\n    }\n    if (animalFlags & AnimalFlags.CanFly) {\n        console.log('animal can fly');\n    }\n    if (animalFlags == AnimalFlags.None){\n        console.log('nothing');\n    }\n}\n\nvar animal = { flags: AnimalFlags.None };\nprintAnimalAbilities(animal); // nothing\nanimal.flags |= AnimalFlags.HasClaws;\nprintAnimalAbilities(animal); // animal has claws\nanimal.flags &= ~AnimalFlags.HasClaws;\nprintAnimalAbilities(animal); // nothing\nanimal.flags |= AnimalFlags.HasClaws | AnimalFlags.CanFly;\nprintAnimalAbilities(animal); // animal has claws, animal can fly\n\n\nnamespace EnumsWithStatics {\n    enum Weekday {\n        Monday,\n        Tuesday,\n        Wednesday,\n        Thursday,\n        Friday,\n        Saturday,\n        Sunday\n    }\n    namespace Weekday {\n        export function isBusinessDay(day: Weekday) {\n            switch (day) {\n                case Weekday.Saturday:\n                case Weekday.Sunday:\n                    return false;\n                default:\n                    return true;\n            }\n        }\n    }\n\n    const mon = Weekday.Monday;\n    const sun = Weekday.Sunday;\n    console.log(Weekday.isBusinessDay(mon)); // true\n    console.log(Weekday.isBusinessDay(sun)); // false\n}\n"
  },
  {
    "path": "code/es6/for..of.js",
    "content": "exports.forof = true;\nvar m0;\n(function (m0) {\n    var someArray = [\n        9,\n        2,\n        5\n    ];\n    for (var item in someArray) {\n        console.log(item);\n    }\n})(m0 || (m0 = {}));\nvar m1;\n(function (m1) {\n    var someArray = [\n        9,\n        2,\n        5\n    ];\n    for (var _i = 0; _i < someArray.length; _i++) {\n        var item = someArray[_i];\n        console.log(item);\n    }\n})(m1 || (m1 = {}));\nvar m2;\n(function (m2) {\n    var hello = \"is it me you're looking for?\";\n    for (var _i = 0; _i < hello.length; _i++) {\n        var char = hello[_i];\n        console.log(char);\n    }\n})(m2 || (m2 = {}));\nvar m2;\n(function (m2) {\n    var articleParagraphs = document.querySelectorAll(\"article > p\");\n    for (var _i = 0; _i < articleParagraphs.length; _i++) {\n        var paragraph = articleParagraphs[_i];\n        paragraph.classList.add(\"read\");\n    }\n})(m2 || (m2 = {}));\n"
  },
  {
    "path": "code/es6/for..of.ts",
    "content": "export var forof = true;\n\nmodule m0 {\n    var someArray = [9, 2, 5];\n    for (var item in someArray) {\n        console.log(item);\n    }\n}\n\nmodule m1 {\n    var someArray = [9, 2, 5];\n    for (var item of someArray) {\n        console.log(item);\n    }\n}\n\nmodule m2 {\n    var hello = \"is it me you're looking for?\";\n    for (var char of hello) {\n        console.log(char); // is it me you're looking for?\n    }\n}\n\nmodule m2 {\n    let articleParagraphs = document.querySelectorAll(\"article > p\");\n    // Error: Nodelist is not an array type or a string type\n    for (let paragraph of articleParagraphs) { \n        paragraph.classList.add(\"read\");\n    }\n}"
  },
  {
    "path": "code/es6/forof.js",
    "content": "exports.forof = true;\nvar m0;\n(function (m0) {\n    var someArray = [\n        9,\n        2,\n        5\n    ];\n    for (var item in someArray) {\n        console.log(item);\n    }\n})(m0 || (m0 = {}));\nvar m1;\n(function (m1) {\n    var someArray = [\n        9,\n        2,\n        5\n    ];\n    for (var _i = 0; _i < someArray.length; _i++) {\n        var item = someArray[_i];\n        console.log(item);\n    }\n})(m1 || (m1 = {}));\nvar m2;\n(function (m2) {\n    var hello = \"is it me you're looking for?\";\n    for (var _i = 0; _i < hello.length; _i++) {\n        var char = hello[_i];\n        console.log(char);\n    }\n})(m2 || (m2 = {}));\nvar m2;\n(function (m2) {\n    var articleParagraphs = document.querySelectorAll(\"article > p\");\n    for (var _i = 0; _i < articleParagraphs.length; _i++) {\n        var paragraph = articleParagraphs[_i];\n        paragraph.classList.add(\"read\");\n    }\n})(m2 || (m2 = {}));\n"
  },
  {
    "path": "code/es6/iterators.js",
    "content": "var Component = (function () {\n    function Component(name) {\n        this.name = name;\n    }\n    return Component;\n}());\nvar Frame = (function () {\n    function Frame(name, components) {\n        this.name = name;\n        this.components = components;\n        this.pointer = 0;\n    }\n    Frame.prototype.next = function () {\n        if (this.pointer < this.components.length) {\n            return {\n                done: false,\n                value: this.components[this.pointer++]\n            };\n        }\n        else\n            return {\n                done: true\n            };\n    };\n    return Frame;\n}());\nvar frame = new Frame(\"Door\", [new Component(\"top\"), new Component(\"bottom\"), new Component(\"left\"), new Component(\"right\")]);\nvar iteratorResult1 = frame.next();\nvar iteratorResult2 = frame.next();\nvar iteratorResult3 = frame.next();\nvar iteratorResult4 = frame.next();\nvar iteratorResult5 = frame.next();\nvar component = iteratorResult1.value;\n"
  },
  {
    "path": "code/es6/iterators.ts",
    "content": "// The book's chapter describes usage of Iterators with ES6 target\n// This example showing usage of iterators with ES5 target\n//\n// The example from the chapter should work in moderen browsers and Node\n// with target ES5 if you add es6.d.ts to the project\n\nclass Component {\n  constructor (public name: string) {}\n}\n\nclass Frame {\n\n  private pointer = 0;\n\n  constructor(public name: string, public components: Component[]) {}\n\n  public next(): {done: boolean, value?: Component} {\n    if (this.pointer < this.components.length) {\n      return {\n        done: false,\n        value: this.components[this.pointer++]\n      }\n    } else return {\n      done: true\n    }\n  }\n\n}\n\nlet frame = new Frame(\"Door\", [new Component(\"top\"), new Component(\"bottom\"), new Component(\"left\"), new Component(\"right\")]);\nlet iteratorResult1 = frame.next(); //{ done: false, value: Component { name: 'top' } }\nlet iteratorResult2 = frame.next(); //{ done: false, value: Component { name: 'bottom' } }\nlet iteratorResult3 = frame.next(); //{ done: false, value: Component { name: 'left' } }\nlet iteratorResult4 = frame.next(); //{ done: false, value: Component { name: 'right' } }\nlet iteratorResult5 = frame.next(); //{ done: true }\n\n//It is possible to access the value of iterator result via the value property:\nlet component = iteratorResult1.value; //Component { name: 'top' }\n"
  },
  {
    "path": "code/es6/let.js",
    "content": "exports.asdfasdfasfadf = 123;\nvar first;\n(function (first) {\n    var something = [\n        1,\n        2,\n        3\n    ];\n})(first || (first = {}));\nvar second;\n(function (second) {\n    var foo = 123;\n    if (true) {\n        var foo = 456;\n    }\n    console.log(foo);\n})(second || (second = {}));\nvar third;\n(function (third) {\n    var foo = 123;\n    function test() {\n        var foo = 456;\n    }\n    test();\n    console.log(foo);\n})(third || (third = {}));\nvar fourth;\n(function (fourth) {\n    var index = 0;\n    var array = [\n        1,\n        2,\n        3\n    ];\n    for (var _index = 0; _index < array.length; _index++) {\n        console.log(array[_index]);\n    }\n    console.log(index);\n})(fourth || (fourth = {}));\nvar fifth;\n(function (fifth) {\n    if (true) {\n        var foo = 123;\n    }\n})(fifth || (fifth = {}));\nvar fifth;\n(function (fifth) {\n    var foo = '123';\n    if (true) {\n        var _foo = 123;\n    }\n})(fifth || (fifth = {}));\nvar closures;\n(function (closures) {\n    var funcs = [];\n    for (var i = 0; i < 3; i++) {\n        funcs.push(function () {\n            console.log(i);\n        });\n    }\n    for (var j = 0; j < 3; j++) {\n        funcs[j]();\n    }\n})(closures || (closures = {}));\nvar closures2;\n(function (closures2) {\n    var funcs = [];\n    for (var i = 0; i < 3; i++) {\n        (function () {\n            var local = i;\n            funcs.push(function () {\n                console.log(local);\n            });\n        })();\n    }\n    for (var j = 0; j < 3; j++) {\n        funcs[j]();\n    }\n})(closures2 || (closures2 = {}));\nvar closures3;\n(function (closures3) {\n    var funcs = [];\n    for (var i = 0; i < 3; i++) {\n        funcs.push(function () {\n            console.log(i);\n        });\n    }\n    for (var j = 0; j < 3; j++) {\n        funcs[j]();\n    }\n})(closures3 || (closures3 = {}));\n"
  },
  {
    "path": "code/es6/let.ts",
    "content": "export var asdfasdfasfadf = 123;\n\nmodule first {\n    let something = [1, 2, 3];\n\n\n}\n\nmodule second {\n    var foo = 123;\n    if (true) {\n        var foo = 456;\n    }\n    console.log(foo); // 456\n}\n\nmodule third {\n    var foo = 123;\n    function test() {\n        var foo = 456;\n    }\n    test();\n    console.log(foo); // 123\n}\n\nmodule fourth {\n    var index = 0;\n    var array = [1, 2, 3];\n    for (let index = 0; index < array.length; index++) {\n        console.log(array[index]);\n    }\n    console.log(index); // 0\n}\n\nmodule fifth {\n    if (true) {\n        let foo = 123;\n    }\n}\n\nmodule fifth {\n    var foo = '123';\n    if (true) {\n        let foo = 123;\n    }\n}\n\nmodule closures {\n    var funcs = [];\n    // create a bunch of functions\n    for (var i = 0; i < 3; i++) {\n        funcs.push(function() {\n            console.log(i);\n        })\n    }\n    // call them\n    for (var j = 0; j < 3; j++) {\n        funcs[j]();\n    }\n}\n\nmodule closures2 {\n    var funcs = [];\n    // create a bunch of functions\n    for (var i = 0; i < 3; i++) {\n        (function() {\n            var local = i;\n            funcs.push(function() {\n                console.log(local);\n            })\n        })();\n    }\n    // call them\n    for (var j = 0; j < 3; j++) {\n        funcs[j]();\n    }\n}\n\nmodule closures3 {\n    var funcs = [];\n    // create a bunch of functions\n    for (let i = 0; i < 3; i++) { // Error : loop contains \n        funcs.push(function() {\n            console.log(i);\n        })\n    }\n    // call them\n    for (var j = 0; j < 3; j++) {\n        funcs[j]();\n    }\n}"
  },
  {
    "path": "code/es6/rest-parameters.js",
    "content": "var rest;\n(function (rest) {\n    function iTakeItAll(first, second) {\n        var allOthers = [];\n        for (var _i = 2; _i < arguments.length; _i++) {\n            allOthers[_i - 2] = arguments[_i];\n        }\n        console.log(allOthers);\n    }\n    iTakeItAll('foo', 'bar');\n    iTakeItAll('foo', 'bar', 'bas', 'qux');\n})(rest = exports.rest || (exports.rest = {}));\n"
  },
  {
    "path": "code/es6/rest-parameters.ts",
    "content": "export module rest {\n    function iTakeItAll(first, second, ...allOthers) {\n        console.log(allOthers);\n    }\n    iTakeItAll('foo', 'bar'); // []\n    iTakeItAll('foo', 'bar', 'bas', 'qux'); // ['bas','qux']    \n}"
  },
  {
    "path": "code/es6/spread-operator.js",
    "content": "var spread;\n(function (spread) {\n    var list = [\n        1,\n        2\n    ];\n    list = list.concat([3, 4]);\n})(spread = exports.spread || (exports.spread = {}));\n"
  },
  {
    "path": "code/es6/spread-operator.ts",
    "content": "export module spread {\n    var list = [1, 2];\n    list = [...list, 3, 4];\n}"
  },
  {
    "path": "code/es6/template-strings.js",
    "content": "exports.templateStrings = '123';\nvar m1;\n(function (m1) {\n    var lyrics = \"Never gonna give you up \\\n\\nNever gonna let you down\";\n    console.log(lyrics);\n})(m1 || (m1 = {}));\nvar m2;\n(function (m2) {\n    var lyrics = \"Never gonna give you up\\nNever gonna let you down\";\n    console.log(lyrics);\n})(m2 || (m2 = {}));\nvar m3;\n(function (m3) {\n    var lyrics = 'Never gonna give you up';\n    var html = '<div>' + lyrics + '</div>';\n})(m3 || (m3 = {}));\nvar m4;\n(function (m4) {\n    var lyrics = 'Never gonna give you up';\n    var html = \"<div>\" + lyrics + \"</div>\";\n})(m4 || (m4 = {}));\nvar m5;\n(function (m5) {\n    console.log(\"1 and 1 one make \" + (1 + 1));\n})(m5 || (m5 = {}));\nvar m6;\n(function (m6) {\n    var say = \"a bird in hand > two in the bush\";\n    var html = (_a = [\"<div> I would just like to say : \", \"</div>\"], _a.raw = [\"<div> I would just like to say : \", \"</div>\"], htmlEscape(_a, say));\n    function htmlEscape(literals) {\n        var placeholders = [];\n        for (var _i = 1; _i < arguments.length; _i++) {\n            placeholders[_i - 1] = arguments[_i];\n        }\n        var result = \"\";\n        for (var i = 0; i < placeholders.length; i++) {\n            result += literals[i];\n            result += placeholders[i].replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n        }\n        result += literals[literals.length - 1];\n        return result;\n    }\n    console.log(html);\n    var _a;\n})(m6 || (m6 = {}));\n"
  },
  {
    "path": "code/es6/template-strings.ts",
    "content": "export var templateStrings = '123';\n\nmodule m1 {\n    var lyrics = \"Never gonna give you up \\\n\\nNever gonna let you down\";\n    console.log(lyrics);\n}\n\nmodule m2 {\n    var lyrics = `Never gonna give you up\nNever gonna let you down`;\n    console.log(lyrics);\n}\n\nmodule m3 {\n    var lyrics = 'Never gonna give you up';\n    var html = '<div>' + lyrics + '</div>';\n}\n\nmodule m4 {\n    var lyrics = 'Never gonna give you up';\n    var html = `<div>${lyrics}</div>`;\n}\n\nmodule m5 {\n    console.log(`1 and 1 one make ${1 + 1}`);\n}\n\nmodule m6 {\n    var say = \"a bird in hand > two in the bush\";\n    var html = htmlEscape `<div> I would just like to say : ${say}</div>`\n    \n    // a sample tag function\n    function htmlEscape(literals, ...placeholders) {\n        let result = \"\";\n\n        // Interleave the literals with the placeholders\n        for (let i = 0; i < placeholders.length; i++) {\n            result += literals[i];\n            result += placeholders[i]\n                .replace(/&/g, '&amp;')\n                .replace(/\"/g, '&quot;')\n                .replace(/'/g, '&#39;')\n                .replace(/</g, '&lt;')\n                .replace(/>/g, '&gt;');\n        }\n\n        // add the last literal\n        result += literals[literals.length - 1];\n        return result;\n    }\n    console.log(html);\n}"
  },
  {
    "path": "code/es6/test.js",
    "content": ""
  },
  {
    "path": "code/es6/test.ts",
    "content": ""
  },
  {
    "path": "code/es6/tsconfig.json",
    "content": "{}\n"
  },
  {
    "path": "code/javascript/closure.js",
    "content": "\"use strict\";\nfunction outerFunction(arg) {\n    var variableInOuterFunction = arg;\n    function bar() {\n        console.log(variableInOuterFunction);\n    }\n    bar();\n}\nouterFunction(\"hello closure\");\nvar another;\n(function (another) {\n    function outerFunction(arg) {\n        var variableInOuterFunction = arg;\n        return function () {\n            console.log(variableInOuterFunction);\n        };\n    }\n    var innerFunction = outerFunction(\"hello closure!\");\n    innerFunction();\n})(another = exports.another || (exports.another = {}));\nvar revealing;\n(function (revealing) {\n    function createCounter() {\n        var val = 0;\n        return {\n            increment: function () { val++; },\n            getVal: function () { return val; }\n        };\n    }\n    var counter = createCounter();\n    counter.increment();\n    console.log(counter.getVal());\n})(revealing = exports.revealing || (exports.revealing = {}));\nvar server;\n(function (server) {\n    server.on(function handler(req, res) {\n        loadData(req.id).then(function (data) {\n            res.send(data);\n        });\n    });\n})(server = exports.server || (exports.server = {}));\n"
  },
  {
    "path": "code/javascript/closure.ts",
    "content": "function outerFunction(arg) {\n    var variableInOuterFunction = arg;\n\n    function bar() {\n        console.log(variableInOuterFunction); // Access a variable from the outer scope\n    }\n\n    // Call the local function to demonstrate that it has access to arg\n    bar();\n}\n\nouterFunction(\"hello closure\"); // logs hello closure!\n\n\nexport namespace another {\n    function outerFunction(arg) {\n        var variableInOuterFunction = arg;\n        return function() {\n            console.log(variableInOuterFunction);\n        }\n    }\n\n    var innerFunction = outerFunction(\"hello closure!\");\n\n    // Note the outerFunction has returned\n    innerFunction(); // logs hello closure!\n}\n\n\nexport namespace revealing {\n    function createCounter() {\n        let val = 0;\n        return {\n            increment() { val++ },\n            getVal() { return val }\n        }\n    }\n\n    let counter = createCounter();\n    counter.increment();\n    console.log(counter.getVal()); // 1\n}\n\nexport namespace server {\n    server.on(function handler(req, res) {\n        loadData(req.id).then(function(data) {\n            // the `res` has been closed over and is available\n            res.send(data);\n        })\n    });\n}\n"
  },
  {
    "path": "code/javascript/tsconfig.json",
    "content": "{\n    \"compilerOptions\": {\n        \"target\": \"es5\",\n        \"module\": \"commonjs\",\n        \"moduleResolution\": \"node\",\n        \"isolatedModules\": false,\n        \"jsx\": \"react\",\n        \"experimentalDecorators\": true,\n        \"emitDecoratorMetadata\": true,\n        \"declaration\": false,\n        \"noImplicitAny\": false,\n        \"noImplicitUseStrict\": false,\n        \"removeComments\": true,\n        \"noLib\": false,\n        \"preserveConstEnums\": true,\n        \"suppressImplicitAnyIndexErrors\": true\n    },\n    \"exclude\": [\n        \"node_modules\",\n        \"typings/browser\",\n        \"typings/browser.d.ts\"\n    ],\n    \"compileOnSave\": true,\n    \"buildOnSave\": false,\n    \"atom\": {\n        \"rewriteTsconfig\": false\n    }\n}\n"
  },
  {
    "path": "code/tips/bindIsBad.js",
    "content": "\"use strict\";\nvar Adder = (function () {\n    function Adder(a) {\n        this.a = a;\n    }\n    Adder.prototype.add = function (b) {\n        return this.a + b;\n    };\n    return Adder;\n})();\nfunction useAdd(add) {\n    return add(456);\n}\nvar adder = new Adder('mary had a little 🐑');\nuseAdd(adder.add.bind(adder));\nuseAdd(function (x) { return adder.add(x); });\nfunction twoParams(a, b) {\n    return a + b;\n}\nvar curryOne = twoParams.bind(null, 123);\ncurryOne(456);\ncurryOne('456');\nvar betterCurry;\n(function (betterCurry) {\n    function twoParams(a, b) {\n        return a + b;\n    }\n    var curryOne = function (x) { return twoParams(123, x); };\n    curryOne(456);\n    curryOne('456');\n})(betterCurry || (betterCurry = {}));\n"
  },
  {
    "path": "code/tips/bindIsBad.ts",
    "content": "export var _asdfasdfsadf;\n\nclass Adder {\n    constructor(public a: string) { }\n\n    add(b: string): string {\n        return this.a + b;\n    }\n}\n\nfunction useAdd(add: (x: number) => number) {\n    return add(456);\n}\n\nlet adder = new Adder('mary had a little 🐑');\nuseAdd(adder.add.bind(adder)); // No compile error!\nuseAdd((x) => adder.add(x)); // Error: number is not assignable to string\n\n\nfunction twoParams(a: number, b: number) {\n    return a + b;\n}\nlet curryOne = twoParams.bind(null, 123);\ncurryOne(456); // Okay but is not type checked!\ncurryOne('456'); // Allowed because it wasn't type checked\n\nnamespace betterCurry {\n    function twoParams(a: number, b: number) {\n        return a + b;\n    }\n    let curryOne = (x: number) => twoParams(123, x);\n    curryOne(456); // Okay and type checked!\n    curryOne('456'); // Error!\n}\n"
  },
  {
    "path": "code/tips/currying.js",
    "content": "\"use strict\";\nvar add = function (x) { return function (y) { return x + y; }; };\nadd(123)(456);\nvar add123 = add(123);\nadd123(456);\n"
  },
  {
    "path": "code/tips/currying.ts",
    "content": "export var _asdfasdfasdf;\n\n\n// A function that supports currying\nlet add = (x: number) => (y: number) => x + y;\n\n// Simple usage\nadd(123)(456);\n\n// curried\nlet add123 = add(123);\n\n// use the curried function\nadd123(456);\n"
  },
  {
    "path": "code/tips/lazyObjectLiteralInitialization.js",
    "content": "\"use strict\";\nvar JS;\n(function (JS) {\n    var foo = {};\n    foo.bar = 123;\n    foo.bas = \"Hello World\";\n})(JS = exports.JS || (exports.JS = {}));\nvar TS;\n(function (TS) {\n    var foo = {\n        bar: 123,\n        bas: \"Hello World\",\n    };\n})(TS = exports.TS || (exports.TS = {}));\nvar TSQuick;\n(function (TSQuick) {\n    var foo = {};\n    foo.bar = 123;\n    foo.bas = \"Hello World\";\n})(TSQuick = exports.TSQuick || (exports.TSQuick = {}));\nvar TSMiddle;\n(function (TSMiddle) {\n    var foo = {};\n    foo.bar = 123;\n    foo.bas = \"Hello World\";\n    foo.bar = 'Hello Stranger';\n})(TSMiddle = exports.TSMiddle || (exports.TSMiddle = {}));\n"
  },
  {
    "path": "code/tips/lazyObjectLiteralInitialization.ts",
    "content": "export namespace JS {\n    let foo = {};\n    foo.bar = 123;\n    foo.bas = \"Hello World\";\n}\n\nexport namespace TS {\n    let foo = {\n        bar: 123,\n        bas: \"Hello World\",\n    };\n}\n\nexport namespace TSQuick {\n    let foo = {} as any;\n    foo.bar = 123;\n    foo.bas = \"Hello World\";\n}\n\nexport namespace TSMiddle {\n    interface Foo {\n        bar: number\n        bas: string\n    }\n\n    let foo = {} as Foo;\n    foo.bar = 123;\n    foo.bas = \"Hello World\";\n\n    // later in the codebase:\n    foo.bar = 'Hello Stranger'; // Error: You probably misspelled `bas` as `bar`, cannot assign string to number\n}\n"
  },
  {
    "path": "code/tips/mixins.js",
    "content": "var __extends = (this && this.__extends) || function (d, b) {\n    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n    function __() { this.constructor = d; }\n    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};\nvar Disposable = (function () {\n    function Disposable() {\n    }\n    Disposable.prototype.dispose = function () {\n        this.isDisposed = true;\n    };\n    return Disposable;\n})();\nvar Activatable = (function () {\n    function Activatable() {\n    }\n    Activatable.prototype.activate = function () {\n        this.isActive = true;\n    };\n    Activatable.prototype.deactivate = function () {\n        this.isActive = false;\n    };\n    return Activatable;\n})();\nvar ActivatibleDisposible = (function () {\n    Disposable.apply(this);\n    ActivatibleDisposible.apply(this);\n    return this;\n});\nvar SmartObject = (function (_super) {\n    __extends(SmartObject, _super);\n    function SmartObject() {\n        var _this = this;\n        _super.call(this);\n        setInterval(function () { return console.log(_this.isActive + \" : \" + _this.isDisposed); }, 500);\n    }\n    SmartObject.prototype.interact = function () {\n        this.activate();\n    };\n    return SmartObject;\n})(ActivatibleDisposible);\napplyMixins(SmartObject, [Disposable, Activatable]);\nvar smartObj = new SmartObject();\nsetTimeout(function () { return smartObj.interact(); }, 1000);\nfunction applyMixins(derivedCtor, baseCtors) {\n    baseCtors.forEach(function (baseCtor) {\n        Object.getOwnPropertyNames(baseCtor.prototype).forEach(function (name) {\n            derivedCtor.prototype[name] = baseCtor.prototype[name];\n        });\n    });\n}\n"
  },
  {
    "path": "code/tips/mixins.ts",
    "content": "// Disposable Mixin\nclass Disposable {\n    isDisposed: boolean;\n    dispose() {\n        this.isDisposed = true;\n    }\n\n}\n \n// Activatable Mixin\nclass Activatable {\n    isActive: boolean;\n    activate() {\n        this.isActive = true;\n    }\n    deactivate() {\n        this.isActive = false;\n    }\n}\n\ninterface ActivatibleDisposible extends Disposable, Activatable {\n    new (): ActivatibleDisposible;\n}\n\nvar ActivatibleDisposible: ActivatibleDisposible = <any>(function(){\n    Disposable.apply(this);\n    ActivatibleDisposible.apply(this);\n    return this;\n})\n\nclass SmartObject extends ActivatibleDisposible {\n    constructor() {\n        super();\n        setInterval(() => console.log(this.isActive + \" : \" + this.isDisposed), 500);\n    }\n\n    interact() {\n        this.activate();\n    }\n}\napplyMixins(SmartObject, [Disposable, Activatable])\n\nvar smartObj = new SmartObject();\nsetTimeout(() => smartObj.interact(), 1000);\n \n////////////////////////////////////////\n// In your runtime library somewhere\n////////////////////////////////////////\n\nfunction applyMixins(derivedCtor: any, baseCtors: any[]) {\n    baseCtors.forEach(baseCtor => {\n        Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {\n            derivedCtor.prototype[name] = baseCtor.prototype[name];\n        })\n    });\n}"
  },
  {
    "path": "code/tips/nominalTyping.js",
    "content": "var EnumDriven;\n(function (EnumDriven) {\n    var FooIdBrand;\n    (function (FooIdBrand) {\n    })(FooIdBrand || (FooIdBrand = {}));\n    var BarIdBrand;\n    (function (BarIdBrand) {\n    })(BarIdBrand || (BarIdBrand = {}));\n    var fooId;\n    var barId;\n    fooId = barId;\n    barId = fooId;\n    fooId = 'foo';\n    barId = 'bar';\n    var str;\n    str = fooId;\n    str = barId;\n})(EnumDriven || (EnumDriven = {}));\nvar Interface;\n(function (Interface) {\n    var fooId;\n    var barId;\n    fooId = barId;\n    barId = fooId;\n    fooId = barId;\n    barId = fooId;\n    fooId = 'foo';\n    barId = 'bar';\n    var str;\n    str = fooId;\n    str = barId;\n})(Interface || (Interface = {}));\n"
  },
  {
    "path": "code/tips/nominalTyping.ts",
    "content": "namespace Literal {\n  /** Generic Id type */\n  type Id<T extends string> = {\n    type: T,\n    value: string,\n  }\n\n  /** Specific Id types */\n  type FooId = Id<'foo'>;\n  type BarId = Id<'bar'>;\n\n  /** Optional: contructors functions */\n  const createFoo = (value: string): FooId => ({ type: 'foo', value });\n  const createBar = (value: string): BarId => ({ type: 'bar', value });\n\n  let foo = createFoo('sample')\n  let bar = createBar('sample');\n\n  foo = bar; // Error\n  foo = foo; // Okay\n}\n\nnamespace EnumDriven {\n  // FOO\n  enum FooIdBrand { }\n  type FooId = FooIdBrand & string;\n\n  // BAR\n  enum BarIdBrand { }\n  type BarId = BarIdBrand & string;\n\n  /**\n   * Usage Demo\n   */\n  var fooId: FooId;\n  var barId: BarId;\n\n  // Safety!\n  fooId = barId; // error\n  barId = fooId; // error\n\n  // Newing up\n  fooId = 'foo' as FooId;\n  barId = 'bar' as BarId;\n\n  // Both types are compatible with the base\n  var str: string;\n  str = fooId;\n  str = barId;\n}\n\nnamespace Interface {\n\n  // FOO\n  interface FooId extends String {\n    _fooIdBrand: string; // To prevent type errors\n  }\n\n  // BAR\n  interface BarId extends String {\n    _barIdBrand: string; // To prevent type errors\n  }\n\n  /**\n   * Usage Demo\n   */\n  var fooId: FooId;\n  var barId: BarId;\n\n  // Safety!\n  fooId = barId; // error\n  barId = fooId; // error\n  fooId = <FooId>barId; // error\n  barId = <BarId>fooId; // error\n\n  // Newing up\n  fooId = 'foo' as any;\n  barId = 'bar' as any;\n\n  // If you need the base string\n  var str: string;\n  str = fooId as any;\n  str = barId as any;\n}\n"
  },
  {
    "path": "code/tips/statefulFunctions.js",
    "content": "var called = (new (function () {\n    function class_1() {\n        var _this = this;\n        this.count = 0;\n        this.called = function () {\n            _this.count++;\n            console.log(\"Called : \" + _this.count);\n        };\n    }\n    return class_1;\n})()).called;\ncalled();\ncalled();\n"
  },
  {
    "path": "code/tips/statefulFunctions.ts",
    "content": "let {called} = new class {\n    count = 0;\n    called = () => {\n        this.count++;\n        console.log(`Called : ${this.count}`);\n    }\n};\n\ncalled(); // Called : 1\ncalled(); // Called : 2\n"
  },
  {
    "path": "code/tips/stringEnums.js",
    "content": "\"use strict\";\nvar Simple;\n(function (Simple) {\n    var Tristate = {\n        False: '',\n        True: '',\n        Unknown: ''\n    };\n    Object.keys(Tristate).map(function (key) { return Tristate[key] = key; });\n    var state = Tristate.True;\n    if (state === Tristate.True) {\n    }\n})(Simple = exports.Simple || (exports.Simple = {}));\nvar Fancy;\n(function (Fancy) {\n    var state;\n    state = 'False';\n})(Fancy = exports.Fancy || (exports.Fancy = {}));\n"
  },
  {
    "path": "code/tips/stringEnums.ts",
    "content": "export namespace Simple {\n    let Tristate = {\n        False: '',\n        True: '',\n        Unknown: ''\n    };\n\n    // make values same as keys\n    Object.keys(Tristate).map((key) => Tristate[key] = key);\n\n\n    /**\n     * Usage\n     */\n\n    // Assigning\n    let state = Tristate.True;\n\n    // Checking if it matches\n    if (state === Tristate.True) {\n\n    }\n}\n\n\nexport namespace Fancy {\n    type TriState = 'False' | 'True' | 'Unknown';\n\n    let state: TriState;\n    state = 'False';\n}\n"
  },
  {
    "path": "code/tips/tsconfig.json",
    "content": "{\n    \"compilerOptions\": {\n        \"target\": \"es5\",\n        \"module\": \"commonjs\",\n        \"declaration\": false,\n        \"noImplicitAny\": false,\n        \"removeComments\": true,\n        \"moduleResolution\": \"node\",\n        \"isolatedModules\": false,\n        \"jsx\": \"react\",\n        \"experimentalDecorators\": true,\n        \"emitDecoratorMetadata\": true,\n        \"noLib\": false,\n        \"preserveConstEnums\": true,\n        \"suppressImplicitAnyIndexErrors\": true\n    },\n    \"filesGlob\": [\n        \"**/*.ts\",\n        \"**/*.tsx\",\n        \"!node_modules/**\"\n    ],\n    \"files\": [\n        \"bindIsBad.ts\",\n        \"currying.ts\",\n        \"lazyObjectLiteralInitialization.ts\",\n        \"mixins.ts\",\n        \"nominalTyping.ts\",\n        \"statefulFunctions.ts\",\n        \"stringEnums.ts\"\n    ],\n    \"exclude\": [],\n    \"atom\": {\n        \"rewriteTsconfig\": true\n    }\n}\n"
  },
  {
    "path": "code/types/assertion.js",
    "content": "exports.asdf = 123;\nvar porting;\n(function (porting) {\n    var foo = {};\n    foo.bar = 123;\n    foo.bas = 'hello';\n})(porting || (porting = {}));\nvar assert;\n(function (assert) {\n    var foo = {};\n    foo.bar = 123;\n    foo.bas = 'hello';\n})(assert || (assert = {}));\nvar sdfsdfsdf;\n(function (sdfsdfsdf) {\n    var foo;\n    var bar = foo;\n})(sdfsdfsdf || (sdfsdfsdf = {}));\nvar doubleAssertion;\n(function (doubleAssertion) {\n    function handler1(event) {\n        var mouseEvent = event;\n    }\n    function handler2(event) {\n        var element = event;\n    }\n    function handler(event) {\n        var element = event;\n    }\n})(doubleAssertion || (doubleAssertion = {}));\n"
  },
  {
    "path": "code/types/assertion.ts",
    "content": "export var asdf = 123;\n\nmodule porting {\n    var foo = {};\n    foo.bar = 123; // error : property 'bar' does not exist on `{}`\n    foo.bas = 'hello'; // error : property 'bas' does not exist on `{}`\n}\n\nmodule assert {\n    interface Foo {\n        bar: number;\n        bas: string;\n    }\n    var foo = {} as Foo;\n    foo.bar = 123;\n    foo.bas = 'hello';\n}\n\nmodule sdfsdfsdf {\n    var foo: any;\n    var bar = <string>foo; // bar is now of type \"string\"\n}\n\n\nnamespace doubleAssertion {\n\n    function handler1(event: Event) {\n        let mouseEvent = event as MouseEvent;\n    }\n\n    function handler2(event: Event) {\n        let element = event as HTMLElement; // Error : Neither 'Event' not type 'HTMLElement' is assignable to the other\n    }\n\n    function handler(event: Event) {\n        let element = event as any as HTMLElement; // Okay!\n    }\n}\n"
  },
  {
    "path": "code/types/callable.ts",
    "content": "export namespace asdfasdfasdfasdflkjasdflkjasdflkjasdflkjasdf {\n}\n\nnamespace A {\n  interface ReturnString {\n    (): string\n  }\n  declare const foo: ReturnString;\n  const bar = foo(); // bar is inferred as a string\n}\n\nnamespace Complex {\n  interface Complex {\n    (foo: string, bar?: number, ...others: boolean[]): number;\n  }\n\n  interface Overloaded {\n    (foo: string): string\n    (foo: number): number\n  }\n\n  // example implementation\n  const overloaded: Overloaded = (foo) => foo;\n\n  // example usage\n  const str = overloaded(''); // str is inferred string\n  const number = overloaded(123); // num is inferred number\n}\n\nnamespace Direct {\n  const overloaded: {\n    (foo: string): string\n    (foo: number): number\n  } = (foo) => foo;\n\n  const simple: (foo: number) => string\n    = (foo) => foo.toString();\n\n  interface CallMeWithNewToGetString {\n    new(): string\n  }\n  // Usage \n  declare const Foo: CallMeWithNewToGetString;\n  const bar = new Foo(); // bar is inferred to be of type string \n}\n\n"
  },
  {
    "path": "code/types/freshness/freshness.js",
    "content": "exports.foo = 123;\nvar first;\n(function (first) {\n    function logName(something) {\n        console.log(something.name);\n    }\n    var person = { name: 'matt', job: 'being awesome' };\n    var animal = { name: 'cow', diet: 'vegan, but has milk of own species' };\n    var random = { note: \"I don't have a name property\" };\n    logName(person);\n    logName(animal);\n    logName(random);\n})(first || (first = {}));\nvar second;\n(function (second) {\n    function logName(something) {\n        console.log(something.name);\n    }\n    logName({ name: 'matt' });\n    logName({ name: 'matt', job: 'being awesome' });\n})(second || (second = {}));\nvar second;\n(function (second) {\n    function logIfHasName(something) {\n        if (something.name) {\n            console.log(something.name);\n        }\n    }\n    var person = { name: 'matt', job: 'being awesome' };\n    var animal = { name: 'cow', diet: 'vegan, but has milk of own species' };\n    var random = { note: \"I don't have a name property\" };\n    logIfHasName(person);\n    logIfHasName(animal);\n    logIfHasName(random);\n    logIfHasName({ neme: 'I just misspelled name to neme' });\n})(second || (second = {}));\n"
  },
  {
    "path": "code/types/freshness/freshness.ts",
    "content": "export var foo = 123;\n\nmodule first {\n\tfunction logName(something: { name: string }) {\n\t\tconsole.log(something.name);\n\t}\n\n\tvar person = { name: 'matt', job: 'being awesome' };\n\tvar animal = { name: 'cow', diet: 'vegan, but has milk of own species' };\n\tvar random = { note: `I don't have a name property` };\n\n\tlogName(person); // okay\n\tlogName(animal); // okay\n\tlogName(random); // Error : property `name` is missing\n}\n\nmodule second {\n\tfunction logName(something: { name: string }) {\n\t\tconsole.log(something.name);\n\t}\n\n\tlogName({ name: 'matt' }); // okay\n\tlogName({ name: 'matt', job: 'being awesome' }); // Error: object literals must only specify known properties. `job` is excessive here.\n}\n\nmodule third {\n\tfunction logIfHasName(something: { name?: string }) {\n\t\tif (something.name) {\n\t\t\tconsole.log(something.name);\n\t\t}\n\t}\n\tvar person = { name: 'matt', job: 'being awesome' };\n\tvar animal = { name: 'cow', diet: 'vegan, but has milk of own species' };\n\n\tlogIfHasName(person); // okay\n\tlogIfHasName(animal); // okay\n\tlogIfHasName({ neme: 'I just misspelled name to neme' }); // Error: object literals must only specify known properties. `neme` is excessive here.\n}\n\nmodule fourth {\n\tvar x: { foo: number; [x: string]: any };\n\tx = { foo: 1, baz: 2 }; // Ok, `baz` matched by index signature\n}\n\nmodule fifth {\n\t// Assuming\n\tinterface State {\n\t\tfoo: string;\n\t\tbar: string;\n\t}\n\n\tclass MyComponent {\n\t\tstate: any;\n\n\t\tsetState(state: State) {\n\t\t\t/* ... */\n\t\t}\n\n\t\tdoSomething() {\n\t\t\t// You want to do:\n\t\t\tthis.setState({ foo: 'Hello' }); // Error: missing property bar\n\n\t\t\t// But because state contains both `foo` and `bar` TypeScript would force you to do:\n\t\t\tthis.setState({ foo: 'Hello', bar: this.state.bar });\n\t\t}\n\t}\n}\n\nmodule sixth {\n\t// Assuming\n\tinterface State {\n\t\tfoo?: string;\n\t\tbar?: string;\n\t}\n\n\tclass MyComponent {\n\t\tstate: any;\n\n\t\tsetState(state: State) {\n\t\t\t/* ... */\n\t\t}\n\n\t\tdoSomething() {\n\t\t\t// You want to do:\n\t\t\tthis.setState({ foo: 'Hello' }); // Yay works fine!\n\n\t\t\t// Because of freshness it's protected against typos as well!\n\t\t\tthis.setState({ foos: 'Hello' }); // Error: Objects may only specify known properties\n\n\t\t\t// And still type checked\n\t\t\tthis.setState({ foo: 123 }); // Error: Cannot assign number to a string\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "code/types/freshness/index-signatures.js",
    "content": "var a;\n(function (a) {\n    var foo = {};\n    foo['Hello'] = 'World';\n    console.log(foo['Hello']);\n})(a || (a = {}));\nvar b;\n(function (b) {\n    var Foo = (function () {\n        function Foo(message) {\n            this.message = message;\n        }\n        ;\n        Foo.prototype.log = function () {\n            console.log(this.message);\n        };\n        return Foo;\n    }());\n    var foo = {};\n    foo['Hello'] = new Foo('World');\n    foo['Hello'].log();\n})(b || (b = {}));\nvar c;\n(function (c) {\n    var obj = {\n        toString: function () {\n            console.log('toString called');\n            return 'Hello';\n        }\n    };\n    var foo = {};\n    foo[obj] = 'World';\n    console.log(foo[obj]);\n    console.log(foo['Hello']);\n})(c || (c = {}));\nvar d;\n(function (d) {\n    var foo = ['World'];\n    console.log(foo[0]);\n})(d || (d = {}));\nvar e;\n(function (e) {\n    var obj = {\n        toString: function () {\n            return 'Hello';\n        }\n    };\n    var foo = {};\n    foo[obj] = 'World';\n    foo[obj.toString()] = 'World';\n})(e || (e = {}));\nvar f;\n(function (f) {\n    var obj = { message: 'Hello' };\n    var foo = {};\n    foo[obj] = 'World';\n    console.log(foo[\"[object Object]\"]);\n})(f || (f = {}));\nvar f;\n(function (f) {\n    console.log((1).toString());\n    console.log((2).toString());\n})(f || (f = {}));\nvar g;\n(function (g) {\n    var foo = {};\n    foo['a'] = { message: 'some message' };\n    foo['a'] = { messages: 'some message' };\n    foo['a'].message;\n    foo['a'].messages;\n})(g || (g = {}));\nvar mustConform2;\n(function (mustConform2) {\n    var foo = { x: 1, y: 2 };\n    foo['x'];\n    var x = 'x';\n    foo[x];\n})(mustConform2 || (mustConform2 = {}));\n"
  },
  {
    "path": "code/types/freshness/index-signatures.ts",
    "content": "module a {\n  let foo: any = {};\n  foo['Hello'] = 'World';\n  console.log(foo['Hello']); // World\n}\nmodule b {\n  class Foo {\n    constructor(public message: string) { };\n    log() {\n      console.log(this.message)\n    }\n  }\n\n  let foo: any = {};\n  foo['Hello'] = new Foo('World');\n  foo['Hello'].log(); // World\n}\nmodule c {\n  let obj = {\n    toString() {\n      console.log('toString called')\n      return 'Hello'\n    }\n  }\n\n  let foo: any = {};\n  foo[obj] = 'World'; // toString called\n  console.log(foo[obj]); // toString called, World\n  console.log(foo['Hello']); // World\n}\n\nmodule d {\n  let foo = ['World'];\n  console.log(foo[0]); // World\n}\n\nmodule e {\n  let obj = {\n    toString() {\n      return 'Hello'\n    }\n  }\n\n  let foo: any = {};\n\n  // ERROR: the index signature must be string, number ...\n  foo[obj] = 'World';\n\n  // FIX: TypeScript forces you to be explicit\n  foo[obj.toString()] = 'World';\n}\n\nmodule f {\n  let obj = { message: 'Hello' }\n  let foo: any = {};\n\n  // ERROR: the index signature must be string, number ...\n  foo[obj] = 'World';\n\n  // Here is what you actually stored!\n  console.log(foo[\"[object Object]\"]); // World\n}\n\nmodule f {\n  console.log((1).toString()); // 1\n  console.log((2).toString()); // 2\n}\n\nmodule g {\n  let foo: { [index: string]: { message: string } } = {};\n\n  /**\n   * Must store stuff that conforms the structure\n   */\n  /** Ok */\n  foo['a'] = { message: 'some message' };\n  /** Error: must contain a `message` or type string. You have a typo in `message` */\n  foo['a'] = { messages: 'some message' };\n\n  /**\n   * Stuff that is read is also type checked\n   */\n  /** Ok */\n  foo['a'].message;\n  /** Error: messages does not exist. You have a typo in `message` */\n  foo['a'].messages;\n}\n\nmodule mustConform {\n\n  /** Okay */\n  interface Foo {\n    [key: string]: number\n    x: number;\n    y: number;\n  }\n  /** Error */\n  interface Bar {\n    [key: string]: number\n    x: number;\n    y: string; // Property `y` must of of type number\n  }\n}\n\nmodule mustConform2 {\n  interface Foo {\n    [key: string]: number\n    x: number;\n  }\n  let foo: Foo = { x: 1, y: 2 };\n  foo['x']; // number\n  let x = 'x'\n  foo[x]; // number\n}\n\nmodule dual {\n  interface ArrStr {\n    [key: string]: string | number; // Must accomodate all members\n\n    [index: number]: string; // Can be a subset of string indexer\n\n    // Just an example member\n    length: number;\n  }\n}\n\nmodule jsland {\n  interface NestedCSS {\n    color?: string;\n    [selector: string]: string | NestedCSS;\n  }\n\n  const example: NestedCSS = {\n    color: 'red',\n    '.subclass': {\n      color: 'blue'\n    }\n  }\n\n  const failsSilently: NestedCSS = {\n    colour: 'red', // No error as `colour` is a valid string selector\n  }\n}\n\nmodule better {\n  interface NestedCSS {\n    color?: string;\n    nest?: {\n      [selector: string]: NestedCSS;\n    }\n  }\n\n  const example: NestedCSS = {\n    color: 'red',\n    nest: {\n      '.subclass': {\n        color: 'blue'\n      }\n    }\n  }\n\n  const failsSilently: NestedCSS = {\n    colour: 'red', // TS Error: unknown property `colour`\n  }\n}"
  },
  {
    "path": "code/types/freshness/tsconfig.json",
    "content": "{\n    \"version\": \"1.5.0-beta\",\n    \"compilerOptions\": {\n        \"target\": \"es5\",\n        \"module\": \"commonjs\",\n        \"isolatedModules\": false,\n        \"jsx\": \"react\",\n        \"experimentalDecorators\": true,\n        \"emitDecoratorMetadata\": true,\n        \"declaration\": false,\n        \"noImplicitAny\": false,\n        \"removeComments\": true,\n        \"noLib\": false,\n        \"preserveConstEnums\": true,\n        \"suppressImplicitAnyIndexErrors\": true\n    },\n    \"filesGlob\": [\n        \"./**/*.ts\",\n        \"./**/*.tsx\",\n        \"!./node_modules/**/*\"\n    ],\n    \"files\": [\n        \"./freshness.ts\",\n        \"./index-signatures.ts\"\n    ],\n    \"atom\": {\n        \"rewriteTsconfig\": true\n    }\n}\n"
  },
  {
    "path": "code/types/functions.js",
    "content": "\"use strict\";\nvar parameter;\n(function (parameter) {\n    var sampleVariable;\n    function foo(sampleParameter) { }\n})(parameter || (parameter = {}));\nvar returnType;\n(function (returnType) {\n    function foo(sample) {\n        return sample;\n    }\n})(returnType || (returnType = {}));\nvar inferred;\n(function (inferred) {\n    function foo(sample) {\n        return sample;\n    }\n})(inferred || (inferred = {}));\nvar misspelled;\n(function (misspelled) {\n    function foo() {\n        return { fou: 'John Doe' };\n    }\n    sendAsJSON(foo());\n})(misspelled || (misspelled = {}));\nvar optional;\n(function (optional) {\n    function foo(bar, bas) {\n    }\n    foo(123);\n    foo(123, 'hello');\n})(optional || (optional = {}));\nvar optionalDefault;\n(function (optionalDefault) {\n    function foo(bar, bas) {\n        if (bas === void 0) { bas = 'world'; }\n        console.log(bar, bas);\n    }\n    foo(123);\n    foo(123, 'hello');\n})(optionalDefault || (optionalDefault = {}));\nvar overloads;\n(function (overloads) {\n    function padding(a, b, c, d) {\n        if (b === undefined && c === undefined && d === undefined) {\n            b = c = d = a;\n        }\n        else if (c === undefined && d === undefined) {\n            c = a;\n            d = b;\n        }\n        return {\n            top: a,\n            right: b,\n            bottom: c,\n            left: d\n        };\n    }\n    overloads.padding = padding;\n})(overloads || (overloads = {}));\nvar overloadsDone;\n(function (overloadsDone) {\n    function padding(a, b, c, d) {\n        if (b === undefined && c === undefined && d === undefined) {\n            b = c = d = a;\n        }\n        else if (c === undefined && d === undefined) {\n            c = a;\n            d = b;\n        }\n        return {\n            top: a,\n            right: b,\n            bottom: c,\n            left: d\n        };\n    }\n    overloadsDone.padding = padding;\n})(overloadsDone || (overloadsDone = {}));\n"
  },
  {
    "path": "code/types/functions.ts",
    "content": "export namespace asdfasdfasdfasdflkjasdflkjasdflkjasdflkjasdf {\n}\n\nnamespace parameter {\n    // variable annotation\n    var sampleVariable: { bar: number }\n\n    // function parameter\n    function foo(sampleParameter: { bar: number }) { }\n}\n\nnamespace returnType {\n    interface Foo {\n        foo: string;\n    }\n\n    // Return type annotated as `: Foo`\n    function foo(sample: Foo) {\n        return sample;\n    }\n}\n\nnamespace inferred {\n    interface Foo {\n        foo: string;\n    }\n\n    function foo(sample: Foo) {\n        return sample; // inferred return type 'Foo'\n    }\n}\n\nnamespace misspelled {\n    function foo() {\n        return { fou: 'John Doe' }; // You might not find this misspelling `foo` till its too late\n    }\n\n    sendAsJSON(foo());\n}\n\nnamespace optional {\n    function foo(bar: number, bas?: string): void {\n        // ..\n    }\n\n    foo(123);\n    foo(123, 'hello');\n}\n\nnamespace optionalDefault {\n    function foo(bar: number, bas: string = 'world') {\n        console.log(bar, bas);\n    }\n\n    foo(123);           // 123, world\n    foo(123, 'hello');  // 123, hello\n}\n\nnamespace overloads {\n    export function padding(a: number, b?: number, c?: number, d?: any) {\n        if (b === undefined && c === undefined && d === undefined) {\n            b = c = d = a;\n        }\n        else if (c === undefined && d === undefined) {\n            c = a;\n            d = b;\n        }\n        return {\n            top: a,\n            right: b,\n            bottom: c,\n            left: d\n        };\n    }\n}\n\nnamespace overloadsDone {\n    export function padding(all: number);\n    export function padding(topAndBottom: number, leftAndRight: number);\n    export function padding(top: number, right: number, bottom: number, left: number);\n    export function padding(a: number, b?: number, c?: number, d?: number) {\n        if (b === undefined && c === undefined && d === undefined) {\n            b = c = d = a;\n        }\n        else if (c === undefined && d === undefined) {\n            c = a;\n            d = b;\n        }\n        return {\n            top: a,\n            right: b,\n            bottom: c,\n            left: d\n        };\n    }\n}\n"
  },
  {
    "path": "code/types/generics.js",
    "content": "var aaa;\n(function (aaa) {\n    var Queue = (function () {\n        function Queue() {\n            var _this = this;\n            this.data = [];\n            this.push = function (item) { return _this.data.push(item); };\n            this.pop = function () { return _this.data.shift(); };\n        }\n        return Queue;\n    }());\n    var queue = new Queue();\n    queue.push(0);\n    queue.push(\"1\");\n    console.log(queue.pop().toPrecision(1));\n    console.log(queue.pop().toPrecision(1));\n})(aaa || (aaa = {}));\nvar bbb;\n(function (bbb) {\n    var QueueNumber = (function () {\n        function QueueNumber() {\n            var _this = this;\n            this.data = [];\n            this.push = function (item) { return _this.data.push(item); };\n            this.pop = function () { return _this.data.shift(); };\n        }\n        return QueueNumber;\n    }());\n    var queue = new QueueNumber();\n    queue.push(0);\n    queue.push(\"1\");\n})(bbb || (bbb = {}));\nvar ccc;\n(function (ccc) {\n    var Queue = (function () {\n        function Queue() {\n            var _this = this;\n            this.data = [];\n            this.push = function (item) { return _this.data.push(item); };\n            this.pop = function () { return _this.data.shift(); };\n        }\n        return Queue;\n    }());\n    var queue = new Queue();\n    queue.push(0);\n    queue.push(\"1\");\n})(ccc || (ccc = {}));\n"
  },
  {
    "path": "code/types/generics.ts",
    "content": "module aaa {\n  class Queue {\n    private data = [];\n    push = (item) => this.data.push(item);\n    pop = () => this.data.shift();\n  }\n\n  const queue = new Queue();\n  queue.push(0);\n  queue.push(\"1\"); // Oops a mistake\n\n  // a developer walks into a bar\n  console.log(queue.pop().toPrecision(1));\n  console.log(queue.pop().toPrecision(1)); // RUNTIME ERROR\n}\n\nmodule bbb {\n  class QueueNumber {\n    private data = [];\n    push = (item: number) => this.data.push(item);\n    pop = (): number => this.data.shift();\n  }\n\n  const queue = new QueueNumber();\n  queue.push(0);\n  queue.push(\"1\"); // ERROR : cannot push a string. Only numbers allowed\n\n  // ^ if that error is fixed the rest would be fine too\n}\n\nmodule ccc {\n  /** A class definition with a generic parameter */\n  class Queue<T> {\n    private data = [];\n    push = (item: T) => this.data.push(item);\n    pop = (): T => this.data.shift();\n  }\n\n  /** Again sample usage */\n  const queue = new Queue<number>();\n  queue.push(0);\n  queue.push(\"1\"); // ERROR : cannot push a string. Only numbers allowed\n\n  // ^ if that error is fixed the rest would be fine too\n}\n\nnamespace ddd {\n  const getJSON = <T>(config: {\n    url: string,\n    headers?: { [key: string]: string },\n  }): Promise<T> => {\n    const fetchConfig = ({\n      method: 'GET',\n      'Accept': 'application/json',\n      'Content-Type': 'application/json',\n      ...(config.headers || {})\n    });\n    return fetch(config.url, fetchConfig)\n      .then<T>(response => response.json());\n  }\n\n  type LoadUsersResponse = {\n    users: {\n      name: string;\n      email: string;\n    }[];\n  };\n  function loadUsers() {\n    return getJSON<LoadUsersResponse>({ url: 'https://example.com/users' });\n  }\n}\n"
  },
  {
    "path": "code/types/interfaces.js",
    "content": "var Implement;\n(function (Implement) {\n    var MyPoint = (function () {\n        function MyPoint() {\n        }\n        return MyPoint;\n    }());\n})(Implement || (Implement = {}));\nvar ErrorIt;\n(function (ErrorIt) {\n    var MyPoint = (function () {\n        function MyPoint() {\n        }\n        return MyPoint;\n    }());\n})(ErrorIt || (ErrorIt = {}));\n"
  },
  {
    "path": "code/types/interfaces.ts",
    "content": "namespace Implement {\n    interface Point {\n        x: number; y: number;\n    }\n\n    class MyPoint implements Point {\n        x: number; y: number; // Same as Point\n    }\n}\n\nnamespace ErrorIt {\n    interface Point {\n        x: number; y: number;\n        z: number; // New member\n    }\n\n    class MyPoint implements Point { // ERROR : missing member `z`\n        x: number; y: number;\n    }\n}\n"
  },
  {
    "path": "code/types/keyof.ts",
    "content": "namespace Test {\n  const colors = {\n    red: 'red',\n    blue: 'blue'\n  }\n  type Colors = keyof typeof colors; \n\n  let color: Colors;\n  color = 'red'; // okay\n  color = 'blue'; // okay\n  color = 'blue'; // Error\n}"
  },
  {
    "path": "code/types/lib/exclude/nolibd.js",
    "content": "var foo = 123;\nvar bar = foo.toString();\n"
  },
  {
    "path": "code/types/lib/exclude/nolibd.ts",
    "content": "var foo = 123; \nvar bar = foo.toString(); // Property 'toString' does not exist on type 'number'."
  },
  {
    "path": "code/types/lib/exclude/tsconfig.json",
    "content": "{\n    \"compilerOptions\":{\n        \"noLib\": true\n    }\n}"
  },
  {
    "path": "code/types/lib/usage/libd.js",
    "content": "var foo = 123;\nvar bar = foo.toString();\nvar test = window;\nwindow.helloWorld = function () { return console.log('hello world'); };\nwindow.helloWorld();\nMath.seedrandom();\nDate.parse;\nString.prototype.endsWith = function (suffix) {\n    var str = this;\n    return str && str.indexOf(suffix, str.length - suffix.length) !== -1;\n};\nconsole.log('foo bar'.endsWith('bas'));\nconsole.log('foo bas'.endsWith('bas'));\n"
  },
  {
    "path": "code/types/lib/usage/libd.ts",
    "content": "var foo = 123;\nvar bar = foo.toString();\n\nvar test = window;\n\ninterface Window {\n    helloWorld(): void;\n}\n\n// Add it at runtime\nwindow.helloWorld = () => console.log('hello world');\n// Call it\nwindow.helloWorld();\n// Misuse it and you get an error: \n// window.helloWorld('gracius'); // Error: Supplied parameters do not match the signature of the call target\n\n\ninterface Math {\n    seedrandom(seed?: string);\n}\n\nMath.seedrandom();\n\nDate.parse\ninterface Date {\n\n}\n\ninterface String {\n    endsWith(suffix: string): boolean;\n}\n\nString.prototype.endsWith = function(suffix: string): boolean {\n    var str: string = this;\n    return str && str.indexOf(suffix, str.length - suffix.length) !== -1;\n}\n\nconsole.log('foo bar'.endsWith('bas')); // false\nconsole.log('foo bas'.endsWith('bas')); // true"
  },
  {
    "path": "code/types/lib/usage/tsconfig.json",
    "content": "{\n    \"compilerOptions\":{\n    }\n}"
  },
  {
    "path": "code/types/libd.js",
    "content": ""
  },
  {
    "path": "code/types/literal-types.js",
    "content": "\"use strict\";\nvar Simple;\n(function (Simple) {\n    var foo;\n    foo = 'Bar';\n})(Simple = exports.Simple || (exports.Simple = {}));\nvar Union;\n(function (Union) {\n    function move(distance, direction) {\n    }\n    move(1, \"North\");\n    move(1, \"Nurth\");\n})(Union = exports.Union || (exports.Union = {}));\n"
  },
  {
    "path": "code/types/literal-types.ts",
    "content": "export namespace Simple {\n  let foo: 'Hello';\n  foo = 'Bar'; // Error: \"Bar\" is not assignable to type \"Hello\"\n}\n\n\nexport namespace Union {\n  type CardinalDirection =\n    \"North\"\n    | \"East\"\n    | \"South\"\n    | \"West\";\n\n  function move(distance: number, direction: CardinalDirection) {\n    // ...\n  }\n\n  move(1, \"North\"); // Okay\n  move(1, \"Nurth\"); // Error!\n}\n\nnamespace StringEnum {\n\n  /** Utility function to create a K:V from a list of strings */\n  function strEnum<T extends string>(o: Array<T>): {[K in T]: K} {\n    return o.reduce((res, key) => {\n      res[key] = key;\n      return res;\n    }, Object.create(null));\n  }\n\n  /**\n   * Sample create a string enum\n   */\n\n  /** Create a K:V */\n  const Direction = strEnum([\n    'North',\n    'South',\n    'East',\n    'West'\n  ])\n  /** Create a Type */\n  type Direction = keyof typeof Direction;\n\n  /** \n   * Sample using a string enum\n   */\n  let sample: Direction;\n\n  sample = Direction.North; // Okay\n  sample = 'North'; // Okay\n  sample = 'AnythingElse'; // ERROR!\n}"
  },
  {
    "path": "code/types/migrating/migrating.js",
    "content": ""
  },
  {
    "path": "code/types/migrating/migrating.ts",
    "content": "declare var $: any;\ndeclare type JQuery = any;"
  },
  {
    "path": "code/types/migrating/tsconfig.json",
    "content": "{}"
  },
  {
    "path": "code/types/readonly.js",
    "content": "\"use strict\";\nvar __extends = (this && this.__extends) || function (d, b) {\n    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n    function __() { this.constructor = d; }\n    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};\nvar Simple;\n(function (Simple) {\n    function foo(config) {\n    }\n    var config = { bar: 123, bas: 123 };\n    foo(config);\n})(Simple = exports.Simple || (exports.Simple = {}));\nvar Type;\n(function (Type) {\n    var foo = { bar: 123, bas: 456 };\n    foo.bar = 456;\n})(Type = exports.Type || (exports.Type = {}));\nvar Class;\n(function (Class) {\n    var Foo = (function () {\n        function Foo() {\n            this.bar = 1;\n            this.baz = \"hello\";\n        }\n        return Foo;\n    }());\n})(Class = exports.Class || (exports.Class = {}));\nvar ReactEx;\n(function (ReactEx) {\n    ;\n    var Something = (function (_super) {\n        __extends(Something, _super);\n        function Something() {\n            _super.apply(this, arguments);\n        }\n        return Something;\n    }(React.Component));\n    ReactEx.Something = Something;\n})(ReactEx = exports.ReactEx || (exports.ReactEx = {}));\nvar Seamless;\n(function (Seamless) {\n    var foo = { 0: 123, 2: 345 };\n    console.log(foo[0]);\n    foo[0] = 456;\n})(Seamless = exports.Seamless || (exports.Seamless = {}));\nvar SeamlessArray;\n(function (SeamlessArray) {\n    var foo = [1, 2, 3];\n    console.log(foo[0]);\n    foo.push(4);\n    foo = foo.concat([4]);\n})(SeamlessArray = exports.SeamlessArray || (exports.SeamlessArray = {}));\nvar ClassGetter;\n(function (ClassGetter) {\n    var Person = (function () {\n        function Person() {\n            this.firstName = \"John\";\n            this.lastName = \"Doe\";\n        }\n        Object.defineProperty(Person.prototype, \"fullName\", {\n            get: function () {\n                return this.firstName + this.lastName;\n            },\n            enumerable: true,\n            configurable: true\n        });\n        return Person;\n    }());\n    var person = new Person();\n    console.log(person.fullName);\n    person.fullName = \"Dear Reader\";\n})(ClassGetter = exports.ClassGetter || (exports.ClassGetter = {}));\nvar vsconst;\n(function (vsconst) {\n    var foo = 123;\n    var bar;\n})(vsconst || (vsconst = {}));\nvar aliasing;\n(function (aliasing) {\n    var foo = {\n        bar: 123\n    };\n    function iMutateFoo(foo) {\n        foo.bar = 456;\n    }\n    iMutateFoo(foo);\n    console.log(foo.bar);\n})(aliasing || (aliasing = {}));\nvar aliasing2;\n(function (aliasing2) {\n    var foo = {\n        bar: 123\n    };\n    function iTakeFoo(foo) {\n        foo.bar = 456;\n    }\n    iTakeFoo(foo);\n})(aliasing2 || (aliasing2 = {}));\n"
  },
  {
    "path": "code/types/readonly.ts",
    "content": "export namespace Simple {\n    function foo(config: {\n        readonly bar: number,\n        readonly bas: number\n    }) {\n        // ..\n    }\n\n    let config = { bar: 123, bas: 123 };\n    foo(config);\n    // You can be sure that `config` isn't changed 🌹\n}\n\nexport namespace Type {\n    type Foo = {\n        readonly bar: number;\n        readonly bas: number;\n    }\n\n    // Initialization is okay\n    let foo: Foo = { bar: 123, bas: 456 };\n\n    // Mutation is not\n    foo.bar = 456; // Error: Left-hand side of assignment expression cannot be a constant or a read-only property\n}\n\n\nexport namespace Class {\n    class Foo {\n        readonly bar = 1; // OK\n        readonly baz: string;\n        constructor() {\n            this.baz = \"hello\";  // OK\n        }\n    }\n}\n\nexport namespace ReactEx {\n    declare namespace React {\n        export class Component<P, U>{ }\n    };\n\n    interface Props {\n        readonly foo: number;\n    }\n    interface State {\n        readonly bar: number;\n    }\n    export class Something extends React.Component<Props, State>{\n        // You can rest assured no one is going to do\n        // this.props.foo = 123; (props are immutable)\n        // this.state.bar = 456; (one should use this.setState)\n    }\n}\n\nexport namespace Seamless {\n    /**\n     * Declaration\n     */\n    interface Foo {\n        readonly[x: number]: number;\n    }\n\n    /**\n     * Usage\n     */\n    let foo: Foo = { 0: 123, 2: 345 };\n    console.log(foo[0]);   // Okay (reading)\n    foo[0] = 456;          // Error (mutating) : Readonly\n}\n\nexport namespace SeamlessArray {\n    let foo: ReadonlyArray<number> = [1, 2, 3];\n    console.log(foo[0]);   // Okay\n    foo.push(4);           // Error: `push` does not exist on ReadonlyArray as it mutates the array\n    foo = foo.concat([4]); // Okay: create a copy\n}\n\n\nexport namespace ClassGetter {\n    class Person {\n        firstName: string = \"John\";\n        lastName: string = \"Doe\";\n        get fullName() {\n            return this.firstName + this.lastName;\n        }\n    }\n\n    const person = new Person();\n    console.log(person.fullName); // John Doe\n    person.fullName = \"Dear Reader\"; // Error! fullName is readonly\n}\n\nnamespace vsconst {\n    const foo = 123;\n    var bar: {\n        readonly bar: number;\n    }\n}\n\nnamespace aliasing {\n    let foo: {\n        readonly bar: number;\n    } = {\n            bar: 123\n        };\n\n    function iMutateFoo(foo: { bar: number }) {\n        foo.bar = 456;\n    }\n\n    iMutateFoo(foo); // The foo argument is aliased by the foo parameter\n    console.log(foo.bar); // 456!\n}\n\nnamespace aliasing2 {\n    interface Foo {\n        readonly bar: number;\n    }\n    let foo: Foo = {\n        bar: 123\n    };\n\n    function iTakeFoo(foo: Foo) {\n        foo.bar = 456; // Error!  bar is readonly\n    }\n\n    iTakeFoo(foo); // The foo argument is aliased by the foo parameter\n}\n"
  },
  {
    "path": "code/types/stringLiteralType.js",
    "content": "\"use strict\";\nvar Simple;\n(function (Simple) {\n    var foo;\n    foo = 'Bar';\n})(Simple = exports.Simple || (exports.Simple = {}));\nvar Union;\n(function (Union) {\n    function move(distance, direction) {\n    }\n    move(1, \"North\");\n    move(1, \"Nurth\");\n})(Union = exports.Union || (exports.Union = {}));\n"
  },
  {
    "path": "code/types/tsconfig.json",
    "content": "{\n    \"compilerOptions\": {\n        \"target\": \"es5\",\n        \"module\": \"commonjs\",\n        \"moduleResolution\": \"node\",\n        \"isolatedModules\": false,\n        \"jsx\": \"react\",\n        \"experimentalDecorators\": true,\n        \"emitDecoratorMetadata\": true,\n        \"declaration\": false,\n        \"noImplicitAny\": false,\n        \"removeComments\": true,\n        \"noLib\": false,\n        \"preserveConstEnums\": true,\n        \"suppressImplicitAnyIndexErrors\": true\n    },\n    \"include\": [\n        \"./**/*.ts\",\n        \"./**/*.tsx\"\n    ],\n    \"atom\": {\n        \"rewriteTsconfig\": false\n    }\n}\n"
  },
  {
    "path": "code/types/type-compatibility.js",
    "content": "\"use strict\";\nvar __extends = (this && this.__extends) || function (d, b) {\n    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n    function __() { this.constructor = d; }\n    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};\nvar InCompat;\n(function (InCompat) {\n    var str = \"Hello\";\n    var num = 123;\n    str = num;\n    num = str;\n})(InCompat = exports.InCompat || (exports.InCompat = {}));\nvar FunctionArgsCount;\n(function (FunctionArgsCount) {\n    var iTakeSomethingAndPassItAnErr = function (x) { };\n    iTakeSomethingAndPassItAnErr(function () { return null; });\n    iTakeSomethingAndPassItAnErr(function (err) { return null; });\n    iTakeSomethingAndPassItAnErr(function (err, data) { return null; });\n    iTakeSomethingAndPassItAnErr(function (err, data, more) { return null; });\n})(FunctionArgsCount = exports.FunctionArgsCount || (exports.FunctionArgsCount = {}));\nvar FunctionReturnCo;\n(function (FunctionReturnCo) {\n    var iMakePoint2D = function () { return ({ x: 0, y: 0 }); };\n    var iMakePoint3D = function () { return ({ x: 0, y: 0, z: 0 }); };\n    iMakePoint2D = iMakePoint3D;\n    iMakePoint3D = iMakePoint2D;\n})(FunctionReturnCo = exports.FunctionReturnCo || (exports.FunctionReturnCo = {}));\nvar FunctionRest;\n(function (FunctionRest) {\n    var foo = function (x, y) { };\n    var bar = function (x, y) { };\n    var bas = function () {\n        var args = [];\n        for (var _i = 0; _i < arguments.length; _i++) {\n            args[_i - 0] = arguments[_i];\n        }\n    };\n    foo = bar = bas;\n    bas = bar = foo;\n})(FunctionRest = exports.FunctionRest || (exports.FunctionRest = {}));\nvar FunctionArgsBi;\n(function (FunctionArgsBi) {\n    var iTakePoint2D = function (point) { };\n    var iTakePoint3D = function (point) { };\n    iTakePoint3D = iTakePoint2D;\n    iTakePoint2D = iTakePoint3D;\n})(FunctionArgsBi = exports.FunctionArgsBi || (exports.FunctionArgsBi = {}));\nvar NominalClassMemebers;\n(function (NominalClassMemebers) {\n    var Animal = (function () {\n        function Animal() {\n        }\n        return Animal;\n    }());\n    var Cat = (function (_super) {\n        __extends(Cat, _super);\n        function Cat() {\n            _super.apply(this, arguments);\n        }\n        return Cat;\n    }(Animal));\n    var animal;\n    var cat;\n    animal = cat;\n    cat = animal;\n    var Size = (function () {\n        function Size() {\n        }\n        return Size;\n    }());\n    var size;\n    animal = size;\n    size = animal;\n})(NominalClassMemebers || (NominalClassMemebers = {}));\nvar invariance;\n(function (invariance) {\n    var Animal = (function () {\n        function Animal(name) {\n            this.name = name;\n        }\n        return Animal;\n    }());\n    var Cat = (function (_super) {\n        __extends(Cat, _super);\n        function Cat() {\n            _super.apply(this, arguments);\n        }\n        Cat.prototype.meow = function () { };\n        return Cat;\n    }(Animal));\n    var animal = new Animal(\"animal\");\n    var cat = new Cat(\"cat\");\n    animal = cat;\n    cat = animal;\n    var animalArr = [animal];\n    var catArr = [cat];\n    catArr = animalArr;\n    catArr[0].meow();\n    animalArr = catArr;\n    animalArr.push(new Animal('another animal'));\n    catArr.forEach(function (c) { return c.meow(); });\n})(invariance = exports.invariance || (exports.invariance = {}));\n"
  },
  {
    "path": "code/types/type-compatibility.ts",
    "content": "export namespace InCompat {\n    let str: string = \"Hello\";\n    let num: number = 123;\n\n    str = num; // ERROR: `number` is not assignable to `string`\n    num = str; // ERROR: `string` is not assignable to `number`\n}\n\nexport namespace FunctionArgsCount {\n    let iTakeSomethingAndPassItAnErr\n        = (x: (err: Error, data: any) => void) => { /* do something */ };\n\n    iTakeSomethingAndPassItAnErr(() => null) // Okay\n    iTakeSomethingAndPassItAnErr((err) => null) // Okay\n    iTakeSomethingAndPassItAnErr((err, data) => null) // Okay\n\n    // ERROR: function may be called with `more` not being passed in\n    iTakeSomethingAndPassItAnErr((err, data, more) => null)\n}\n\nexport namespace FunctionReturnCo {\n    /** Type Heirarchy */\n    interface Point2D { x: number; y: number; }\n    interface Point3D { x: number; y: number; z: number; }\n\n    /** Two sample functions */\n    let iMakePoint2D = (): Point2D => ({ x: 0, y: 0 });\n    let iMakePoint3D = (): Point3D => ({ x: 0, y: 0, z: 0 });\n\n    /** Assignment */\n    iMakePoint2D = iMakePoint3D; // Okay\n    iMakePoint3D = iMakePoint2D; // ERROR: Point2D is not assignable to Point3D\n}\n\nexport namespace FunctionRest {\n    let foo = (x:number, y: number) => { /* do something */ }\n    let bar = (x?:number, y?: number) => { /* do something */ }\n    let bas = (...args: number[]) => { /* do something */ }\n\n    foo = bar = bas;\n    bas = bar = foo;\n}\n\nexport namespace FunctionArgsBi {\n    /** Type Heirarchy */\n    interface Point2D { x: number; y: number; }\n    interface Point3D { x: number; y: number; z: number; }\n\n    /** Two sample functions */\n    let iTakePoint2D = (point: Point2D) => { /* do something */ }\n    let iTakePoint3D = (point: Point3D) => { /* do something */ }\n\n    iTakePoint3D = iTakePoint2D; // Okay : Reasonalble\n    iTakePoint2D = iTakePoint3D; // Okay : WHAT\n}\n\nnamespace NominalClassMemebers {\n    /** A class hierarchy */\n    class Animal { protected feet: number; }\n    class Cat extends Animal { }\n\n    let animal: Animal;\n    let cat: Cat;\n\n    animal = cat; // OKAY\n    cat = animal; // OKAY\n\n    /** Looks just like Animal */\n    class Size { protected feet: number; }\n\n    let size: Size;\n\n    animal = size; // ERROR\n    size = animal; // ERROR\n}\n\n\nexport namespace invariance {\n    /** Heirarchy */\n    class Animal { constructor(public name: string){} }\n    class Cat extends Animal { meow() { } }\n\n    /** An item of each */\n    var animal = new Animal(\"animal\");\n    var cat = new Cat(\"cat\");\n\n    /**\n     * Demo : polymorphism 101\n     * Animal <= Cat\n     */\n    animal = cat; // Okay\n    cat = animal; // ERROR: cat extends animal\n\n    /** Array of each to demonstrate variance */\n    let animalArr: Animal[] = [animal];\n    let catArr: Cat[] = [cat];\n\n    /**\n     * Obviously Bad : Contravariance\n     * Animal <= Cat\n     * Animal[] >= Cat[]\n     */\n    catArr = animalArr; // Okay if contravariant\n    catArr[0].meow(); // Allowed but BANG 🔫 at runtime\n\n\n    /**\n     * Also Bad : covariance\n     * Animal <= Cat\n     * Animal[] <= Cat[]\n     */\n    animalArr = catArr; // Okay if covariant\n    animalArr.push(new Animal('another animal')); // Just pushed an animal into catArr too!\n    catArr.forEach(c => c.meow()); // Allowed but BANG 🔫 at runtime\n\n}\n"
  },
  {
    "path": "code/types/type-inference.js",
    "content": "var Definition;\n(function (Definition) {\n    var foo = 123;\n    var bar = \"Hello\";\n    foo = bar;\n})(Definition || (Definition = {}));\nvar ReturnType;\n(function (ReturnType) {\n    function add(a, b) {\n        return a + b;\n    }\n})(ReturnType || (ReturnType = {}));\nvar Assignment;\n(function (Assignment) {\n    var foo = function (a, b) { return a + b; };\n})(Assignment || (Assignment = {}));\nvar AssignmentErrorOut;\n(function (AssignmentErrorOut) {\n    var foo = function (a, b) {\n        a = \"hello\";\n        return a + b;\n    };\n})(AssignmentErrorOut || (AssignmentErrorOut = {}));\nvar AssignmentAsCallback;\n(function (AssignmentAsCallback) {\n    function iTakeAnAdder(adder) {\n        return adder(1, 2);\n    }\n    iTakeAnAdder(function (a, b) {\n        return a + b;\n    });\n})(AssignmentAsCallback || (AssignmentAsCallback = {}));\nvar Structuring;\n(function (Structuring) {\n    var foo = {\n        a: 123,\n        b: 456\n    };\n    var bar = [1, 2, 3];\n})(Structuring || (Structuring = {}));\nvar StructuringDeep;\n(function (StructuringDeep) {\n    var foo = {\n        bar: [1, 3, 4]\n    };\n    foo.bar[0] = 'hello';\n})(StructuringDeep || (StructuringDeep = {}));\nvar DeStructuring;\n(function (DeStructuring) {\n    var foo = {\n        a: 123,\n        b: 456\n    };\n    var a = foo.a;\n})(DeStructuring || (DeStructuring = {}));\nvar DeStructuringArrays;\n(function (DeStructuringArrays) {\n    var bar = [1, 2];\n    var a = bar[0], b = bar[1];\n})(DeStructuringArrays || (DeStructuringArrays = {}));\nvar DeStructuringArguments;\n(function (DeStructuringArguments) {\n    function iTakeAnAdder(adder) {\n        return adder({ a: 1, b: 2 });\n    }\n    iTakeAnAdder(function (_a) {\n        var a = _a.a, b = _a.b;\n        return a + b;\n    });\n})(DeStructuringArguments || (DeStructuringArguments = {}));\nvar CantInferArguments;\n(function (CantInferArguments) {\n    var foo = function (a, b) { };\n})(CantInferArguments || (CantInferArguments = {}));\nvar CanInferArguments;\n(function (CanInferArguments) {\n    var foo = function (a, b) { };\n})(CanInferArguments || (CanInferArguments = {}));\nvar CannotInferReturn;\n(function (CannotInferReturn) {\n    function foo(a, b) {\n        return a + addOne(b);\n    }\n    function addOne(a) {\n        return a + 1;\n    }\n})(CannotInferReturn || (CannotInferReturn = {}));\n"
  },
  {
    "path": "code/types/type-inference.ts",
    "content": "namespace Definition {\n    let foo = 123; // foo is a `number`\n    let bar = \"Hello\"; // bar is a `string`\n    foo = bar; // Error: cannot assign `string` to a `number`\n\n}\n\nnamespace ReturnType {\n    function add(a: number, b: number) {\n        return a + b;\n    }\n}\n\nnamespace Assignment {\n    type Adder = (a: number, b: number) => number;\n    let foo: Adder = (a, b) => a + b;\n}\n\nnamespace AssignmentErrorOut {\n    type Adder = (a: number, b: number) => number;\n    let foo: Adder = (a, b) => {\n        a = \"hello\"; // Error: cannot assign `string` to a `number`\n        return a + b;\n    }\n}\n\nnamespace AssignmentAsCallback {\n    type Adder = (a: number, b: number) => number;\n    function iTakeAnAdder(adder: Adder) {\n        return adder(1, 2);\n    }\n    iTakeAnAdder((a, b) => {\n        // a = \"hello\"; // Would Error: cannot assign `string` to a `number`\n        return a + b;\n    })\n}\n\nnamespace Structuring {\n    let foo = {\n        a: 123,\n        b: 456\n    };\n    // foo.a = \"hello\"; // Would Error: cannot assign `string` to a `number`\n\n    const bar = [1, 2, 3];\n    // bar[0] = \"hello\"; // Would error: cannot assign `string` to a `number`\n}\n\nnamespace StructuringDeep {\n    let foo = {\n        bar: [1, 3, 4]\n    };\n    foo.bar[0] = 'hello'; // Would error: cannot assign `string` to a `number`\n}\n\nnamespace DeStructuring {\n    let foo = {\n        a: 123,\n        b: 456\n    };\n    let {a} = foo;\n    // a = \"hello\"; // Would Error: cannot assign `string` to a `number`\n}\n\nnamespace DeStructuringArrays {\n    const bar = [1, 2];\n    let [a, b] = bar;\n    // a = \"hello\"; // Would Error: cannot assign `string` to a `number`\n}\n\nnamespace DeStructuringArguments {\n    type Adder = (numbers: { a: number, b: number }) => number;\n    function iTakeAnAdder(adder: Adder) {\n        return adder({ a: 1, b: 2 });\n    }\n    iTakeAnAdder(({a, b}) => { // Types of `a` and `b` are inferred\n        // a = \"hello\"; // Would Error: cannot assign `string` to a `number`\n        return a + b;\n    })\n}\n\n\nnamespace CantInferArguments {\n    const foo = (a, b) => { /* do something */ };\n}\n\n\nnamespace CanInferArguments {\n    type TwoNumberFunction = (a: number, b: number) => void;\n    const foo: TwoNumberFunction = (a, b) => { /* do something */ };\n}\n\nnamespace CannotInferReturn {\n    function foo(a: number, b: number) {\n        return a + addOne(b);\n    }\n    function addOne(a) {\n        return a + 1;\n    }\n}\n"
  },
  {
    "path": "code/types/typeGuard.js",
    "content": "\"use strict\";\nvar quick;\n(function (quick) {\n    function doSomething(x) {\n        if (typeof x === 'string') {\n            console.log(x.subtr(1));\n            console.log(x.substr(1));\n        }\n        x.substr(1);\n    }\n})(quick = exports.quick || (exports.quick = {}));\nvar instance;\n(function (instance) {\n    var Foo = (function () {\n        function Foo() {\n            this.foo = 123;\n            this.common = '123';\n        }\n        return Foo;\n    }());\n    var Bar = (function () {\n        function Bar() {\n            this.bar = 123;\n            this.common = '123';\n        }\n        return Bar;\n    }());\n    function doStuff(arg) {\n        if (arg instanceof Foo) {\n            console.log(arg.foo);\n            console.log(arg.bar);\n        }\n        if (arg instanceof Bar) {\n            console.log(arg.foo);\n            console.log(arg.bar);\n        }\n        console.log(arg.common);\n        console.log(arg.foo);\n        console.log(arg.bar);\n    }\n    doStuff(new Foo());\n    doStuff(new Bar());\n})(instance = exports.instance || (exports.instance = {}));\nvar instanceElse;\n(function (instanceElse) {\n    var Foo = (function () {\n        function Foo() {\n            this.foo = 123;\n        }\n        return Foo;\n    }());\n    var Bar = (function () {\n        function Bar() {\n            this.bar = 123;\n        }\n        return Bar;\n    }());\n    function doStuff(arg) {\n        if (arg instanceof Foo) {\n            console.log(arg.foo);\n            console.log(arg.bar);\n        }\n        else {\n            console.log(arg.foo);\n            console.log(arg.bar);\n        }\n    }\n    doStuff(new Foo());\n    doStuff(new Bar());\n})(instanceElse = exports.instanceElse || (exports.instanceElse = {}));\nvar userDefined;\n(function (userDefined) {\n    function isFoo(arg) {\n        return arg.foo !== undefined;\n    }\n    function doStuff(arg) {\n        if (isFoo(arg)) {\n            console.log(arg.foo);\n            console.log(arg.bar);\n        }\n        else {\n            console.log(arg.foo);\n            console.log(arg.bar);\n        }\n    }\n    doStuff({ foo: 123, common: '123' });\n    doStuff({ bar: 123, common: '123' });\n})(userDefined = exports.userDefined || (exports.userDefined = {}));\n"
  },
  {
    "path": "code/types/typeGuard.ts",
    "content": "export namespace quick {\n    function doSomething(x: number | string) {\n        if (typeof x === 'string') { // Within the block TypeScript knows that `x` must be a string\n            console.log(x.subtr(1)); // Error, 'subtr' does not exist on `string`\n            console.log(x.substr(1)); // OK\n        }\n        x.substr(1); // Error: There is no guarantee that `x` is a `string`\n    }\n}\n\nexport namespace instance {\n    class Foo {\n        foo = 123;\n        common = '123';\n    }\n\n    class Bar {\n        bar = 123;\n        common = '123';\n    }\n\n    function doStuff(arg: Foo | Bar) {\n        if (arg instanceof Foo){\n            console.log(arg.foo); // OK\n            console.log(arg.bar); // Error!\n        }\n        if (arg instanceof Bar){\n            console.log(arg.foo); // Error!\n            console.log(arg.bar); // OK\n        }\n\n        console.log(arg.common); // OK\n        console.log(arg.foo); // Error!\n        console.log(arg.bar); // Error!\n    }\n\n    doStuff(new Foo());\n    doStuff(new Bar());\n}\n\nexport namespace instanceElse {\n    class Foo {\n        foo = 123;\n    }\n\n    class Bar {\n        bar = 123;\n    }\n\n    function doStuff(arg: Foo | Bar) {\n        if (arg instanceof Foo){\n            console.log(arg.foo); // OK\n            console.log(arg.bar); // Error!\n        }\n        else {  // MUST BE Bar!\n            console.log(arg.foo); // Error!\n            console.log(arg.bar); // OK\n        }\n    }\n\n    doStuff(new Foo());\n    doStuff(new Bar());\n}\n\n\nexport namespace userDefined {\n    /**\n     * Just some interfaces\n     */\n    interface Foo {\n        foo: number;\n        common: string;\n    }\n\n    interface Bar {\n        bar: number;\n        common: string;\n    }\n\n    /**\n     * User Defined Type Guard!\n     */\n    function isFoo(arg: any): arg is Foo {\n        return arg.foo !== undefined;\n    }\n\n    /**\n     * Sample usage of the User Defined Type Guard\n     */\n    function doStuff(arg: Foo | Bar) {\n        if (isFoo(arg)) {\n            console.log(arg.foo); // OK\n            console.log(arg.bar); // Error!\n        }\n        else {\n            console.log(arg.foo); // Error!\n            console.log(arg.bar); // OK\n        }\n    }\n\n    doStuff({foo:123,common:'123'});\n    doStuff({bar:123,common:'123'});\n}\n"
  },
  {
    "path": "code/types/types.js",
    "content": "var typeannotations;\n(function (typeannotations) {\n    var num = 123;\n    function identity(num) {\n        return num;\n    }\n})(typeannotations = exports.typeannotations || (exports.typeannotations = {}));\nvar m1;\n(function (m1) {\n    var num;\n    var str;\n    var bool;\n    num = 123;\n    num = 123.456;\n    num = '123';\n    str = '123';\n    str = 123;\n    bool = true;\n    bool = false;\n    bool = 'false';\n})(m1 = exports.m1 || (exports.m1 = {}));\nvar m2;\n(function (m2) {\n    var boolArray;\n    boolArray = [\n        true,\n        false\n    ];\n    console.log(boolArray[0]);\n    console.log(boolArray.length);\n    boolArray[1] = true;\n    boolArray = [\n        false,\n        false\n    ];\n    boolArray[0] = 'false';\n    boolArray = 'false';\n    boolArray = [\n        true,\n        'false'\n    ];\n})(m2 = exports.m2 || (exports.m2 = {}));\nvar m3;\n(function (m3) {\n    var name;\n    name = {\n        first: 'John',\n        second: 'Doe'\n    };\n    name = {\n        first: 'John'\n    };\n    name = {\n        first: 'John',\n        second: 1337\n    };\n})(m3 = exports.m3 || (exports.m3 = {}));\nvar m4;\n(function (m4) {\n    var name;\n    name = {\n        first: 'John',\n        second: 'Doe'\n    };\n    name = {\n        first: 'John'\n    };\n    name = {\n        first: 'John',\n        second: 1337\n    };\n})(m4 = exports.m4 || (exports.m4 = {}));\nvar any;\n(function (any) {\n    var power;\n    power = '123';\n    power = 123;\n    var num;\n    power = num;\n    num = power;\n})(any || (any = {}));\nvar null_undefined;\n(function (null_undefined) {\n    var num;\n    var str;\n    num = null;\n    str = undefined;\n    foo: Null;\n    bar: Undefined;\n})(null_undefined || (null_undefined = {}));\nvar void_;\n(function (void_) {\n    function log(message) {\n        console.log(message);\n    }\n})(void_ || (void_ = {}));\nvar generics;\n(function (generics) {\n    function reverse(items) {\n        var toreturn = [];\n        for (var i = items.length - 1; i >= 0; i--) {\n            toreturn.push(items[i]);\n        }\n        return toreturn;\n    }\n    var sample = [\n        1,\n        2,\n        3\n    ];\n    var reversed = reverse(sample);\n    console.log(reversed);\n    reversed[0] = '1';\n    reversed = [\n        '1',\n        '2'\n    ];\n    reversed[0] = 1;\n    reversed = [\n        1,\n        2\n    ];\n    var strArr = [\n        '1',\n        '2'\n    ];\n    var reversedStrs = reverse(strArr);\n    reversedStr = [\n        1,\n        2\n    ];\n    var numArr = [\n        1,\n        2\n    ];\n    var reversedNums = numArr.reverse();\n    reversedNums = [\n        '1',\n        '2'\n    ];\n})(generics || (generics = {}));\nvar union;\n(function (union) {\n    function formatCommandline(command) {\n        var line = '';\n        if (typeof command === 'string') {\n            line = command.trim();\n        }\n        else {\n            line = command.join(' ').trim();\n        }\n    }\n})(union || (union = {}));\nvar tuple;\n(function (tuple) {\n    var nameNumber;\n    nameNumber = [\n        'Jenny',\n        8675309\n    ];\n    nameNumber = [\n        'Jenny',\n        '867-5309'\n    ];\n    var name = nameNumber[0], num = nameNumber[1];\n})(tuple || (tuple = {}));\nvar getset;\n(function (getset) {\n    var _value;\n    function getOrSet(value) {\n        if (value === undefined) {\n            return _value;\n        }\n        else {\n            _value = value;\n        }\n    }\n    getOrSet(1);\n    console.log(getOrSet());\n})(getset || (getset = {}));\nvar getset_;\n(function (getset_) {\n    var _value;\n    function getOrSet(value) {\n        if (value === undefined) {\n            return _value;\n        }\n        else {\n            _value = value;\n        }\n    }\n    getOrSet(1);\n    console.log(getOrSet());\n})(getset_ || (getset_ = {}));\nvar overload;\n(function (overload) {\n    function callMe(v1, v2) {\n    }\n    callMe();\n    callMe(1);\n    callMe('jenny', 5309);\n    callMe('jenny');\n    callMe('jenny', '5309');\n})(overload || (overload = {}));\nvar alias;\n(function (alias) {\n    var sample;\n    sample = 123;\n    sample = '123';\n    sample = true;\n})(alias || (alias = {}));\n"
  },
  {
    "path": "code/types/types.ts",
    "content": "export module typeannotations {\n    var num: number = 123;\n    function identity(num: number): number {\n        return num;\n    }\n}\n\nexport module m1 {\n    var num: number;\n    var str: string;\n    var bool: boolean;\n\n    num = 123;\n    num = 123.456;\n    num = '123'; // Error\n\n    str = '123';\n    str = 123; // Error\n\n    bool = true;\n    bool = false;\n    bool = 'false'; // Error\n}\n\nexport module m2 {\n    var boolArray: boolean[];\n\n    boolArray = [true, false];\n    console.log(boolArray[0]); // true\n    console.log(boolArray.length); // 2\n    boolArray[1] = true;\n    boolArray = [false, false];\n\n    boolArray[0] = 'false'; // Error!\n    boolArray = 'false'; // Error!\n    boolArray = [true, 'false']; // Error!\n}\n\nexport module m3 {\n    interface Name {\n        first: string;\n        second: string;\n    }\n\n    var name: Name;\n    name = {\n        first: 'John',\n        second: 'Doe'\n    };\n\n    name = {           // Error : `second` is missing\n        first: 'John'\n    };\n    name = {           // Error : `second` is the wrong type\n        first: 'John',\n        second: 1337\n    };\n}\n\nexport module m4 {\n    var name: {\n        first: string;\n        second: string;\n    };\n    name = {\n        first: 'John',\n        second: 'Doe'\n    };\n\n    name = {           // Error : `second` is missing\n        first: 'John'\n    };\n    name = {           // Error : `second` is the wrong type\n        first: 'John',\n        second: 1337\n    };\n}\n\nmodule any {\n    var power: any;\n\n    // Takes any and all types\n    power = '123';\n    power = 123;\n\n    // Is compatible with all types\n    var num: number;\n    power = num;\n    num = power;\n}\n\nmodule null_undefined {\n    var num: number;\n    var str: string;\n\n    // These literals can be assigned to anything\n    num = null;\n    str = undefined;\n\n    // However they don't have a dedicated annotation\n    foo: Null; // Error\n    bar: Undefined; // Error\n}\n\nmodule void_ {\n    function log(message): void {\n        console.log(message);\n    }\n}\n\nmodule generics {\n    function reverse<T>(items: T[]): T[] {\n        var toreturn = [];\n        for (let i = items.length - 1; i >= 0; i--) {\n            toreturn.push(items[i]);\n        }\n        return toreturn;\n    }\n\n    var sample = [1, 2, 3];\n    var reversed = reverse(sample);\n    console.log(reversed); // 3,2,1\n\n    // Safety!\n    reversed[0] = '1';     // Error!\n    reversed = ['1', '2']; // Error!\n\n    reversed[0] = 1;       // Okay\n    reversed = [1, 2];     // Okay\n\n    //////////////////////\n\n    var strArr = ['1', '2'];\n    var reversedStrs = reverse(strArr);\n\n    reversedStrs = [1, 2]; // Error!\n\n    ///\n    var numArr = [1, 2];\n    var reversedNums = numArr.reverse();\n\n    reversedNums = ['1', '2']; // Error!\n}\n\nmodule union {\n    function formatCommandline(command: string[]|string) {\n        var line = '';\n        if (typeof command === 'string') {\n            line = command.trim();\n        } else {\n            line = command.join(' ').trim();\n        }\n\n        // Do stuff with line:string\n    }\n}\n\nmodule tuple {\n    var nameNumber: [string, number];\n\n    // Okay\n    nameNumber = ['Jenny', 8675309];\n\n    // Error!\n    nameNumber = ['Jenny', '867-5309'];\n\n    var [name, num] = nameNumber;\n}\n\nmodule getset {\n\n    var _value;\n    function getOrSet(value) {\n        if (value === undefined) {\n            return _value;\n        } else {\n            _value = value;\n        }\n    }\n\n    getOrSet(1); // set : 1\n    console.log(getOrSet()); // get : 1\n}\n\nmodule getset_ {\n\n    var _value;\n    function getOrSet(): number;\n    function getOrSet(value: number);\n    function getOrSet(value?: number) {\n        if (value === undefined) {\n            return _value;\n        } else {\n            _value = value;\n        }\n    }\n\n    getOrSet(1); // set : 1\n    console.log(getOrSet()); // get : 1\n}\n\n\nmodule overload {\n\n    function callMe(): number;\n    function callMe(v1: number);\n    function callMe(v1: string, v2: number);\n    function callMe(v1?: any, v2?: any): any {\n        // Implementation body goes here\n    }\n\n    // Allowed calls\n    callMe();\n    callMe(1);\n    callMe('jenny', 5309);\n\n    // ERROR: invalid calls:\n    callMe('jenny');\n    callMe('jenny', '5309');\n}\n\nmodule alias {\n    type StrOrNum = string|number;\n\n    var sample: StrOrNum;\n    sample = 123;\n    sample = '123';\n\n    // Safety\n    sample = true; // Error!\n}\n"
  },
  {
    "path": "docs/arrow-functions.md",
    "content": "* [Arrow Functions](#arrow-functions)\n* [Tip: Arrow Function Need](#tip-arrow-function-need)\n* [Tip: Arrow Function Danger](#tip-arrow-function-danger)\n* [Tip: Libraries that use `this`](#tip-arrow-functions-with-libraries-that-use-this)\n* [Tip: Arrow Function inheritance](#tip-arrow-functions-and-inheritance)\n* [Tip: Quick object return](#tip-quick-object-return)\n\n### Arrow Functions\n\nLovingly called the *fat arrow* (because `->` is a thin arrow and `=>` is a fat arrow) and also called a *lambda function* (because of other languages). Another commonly used feature is the fat arrow function `()=>something`. The motivation for a *fat arrow* is:\n\n1. You don't need to keep typing `function`\n1. It lexically captures the meaning of `this`\n1. It lexically captures the meaning of `arguments`\n\nFor a language that claims to be functional, in JavaScript you tend to be typing `function` quite a lot. The fat arrow makes it simple for you to create a function\n```ts\nvar inc = (x)=>x+1;\n```\n`this` has traditionally been a pain point in JavaScript. As a wise man once said \"I hate JavaScript as it tends to lose the meaning of `this` all too easily\". Fat arrows fix it by capturing the meaning of `this` from the surrounding context. Consider this pure JavaScript class:\n\n```ts\nfunction Person(age) {\n    this.age = age;\n    this.growOld = function() {\n        this.age++;\n    }\n}\nvar person = new Person(1);\nsetTimeout(person.growOld,1000);\n\nsetTimeout(function() { console.log(person.age); },2000); // 1, should have been 2\n```\nIf you run this code in the browser `this` within the function is going to point to `window` because `window` is going to be what executes the `growOld` function. Fix is to use an arrow function:\n```ts\nfunction Person(age) {\n    this.age = age;\n    this.growOld = () => {\n        this.age++;\n    }\n}\nvar person = new Person(1);\nsetTimeout(person.growOld,1000);\n\nsetTimeout(function() { console.log(person.age); },2000); // 2\n```\nThe reason why this works is the reference to `this` is captured by the arrow function from outside the function body. This is equivalent to the following JavaScript code (which is what you would write yourself if you didn't have TypeScript):\n```ts\nfunction Person(age) {\n    this.age = age;\n    var _this = this;  // capture this\n    this.growOld = function() {\n        _this.age++;   // use the captured this\n    }\n}\nvar person = new Person(1);\nsetTimeout(person.growOld,1000);\n\nsetTimeout(function() { console.log(person.age); },2000); // 2\n```\nNote that since you are using TypeScript you can be even sweeter in syntax and combine arrows with classes:\n```ts\nclass Person {\n    constructor(public age:number) {}\n    growOld = () => {\n        this.age++;\n    }\n}\nvar person = new Person(1);\nsetTimeout(person.growOld,1000);\n\nsetTimeout(function() { console.log(person.age); },2000); // 2\n```\n\n> [A sweet video about this pattern 🌹](https://egghead.io/lessons/typescript-make-usages-of-this-safe-in-class-methods)\n\n#### Tip: Arrow Function Need\nBeyond the terse syntax, you only *need* to use the fat arrow if you are going to give the function to someone else to call. Effectively:\n```ts\nvar growOld = person.growOld;\n// Then later someone else calls it:\ngrowOld();\n```\nIf you are going to call it yourself, i.e.\n```ts\nperson.growOld();\n```\nthen `this` is going to be the correct calling context (in this example `person`).\n\n#### Tip: Arrow Function Danger\n\nIn fact if you want `this` *to be the calling context* you should *not use the arrow function*. This is the case with callbacks used by libraries like jquery, underscore, mocha and others. If the documentation mentions functions on `this` then you should probably just use a `function` instead of a fat arrow. Similarly if you plan to use `arguments` don't use an arrow function.\n\n#### Tip: Arrow functions with libraries that use `this`\nMany libraries do this e.g. `jQuery` iterables (one example https://api.jquery.com/jquery.each/) will use `this` to pass you the object that it is currently iterating over. In this case if you want to access the library passed `this` as well as the surrounding context just use a temp variable like `_self` like you would in the absence of arrow functions.\n\n```ts\nlet _self = this;\nsomething.each(function() {\n    console.log(_self); // the lexically scoped value\n    console.log(this); // the library passed value\n});\n```\n\n#### Tip: Arrow functions and inheritance\nArrow functions as properties on classes work fine with inheritance: \n\n```ts\nclass Adder {\n    constructor(public a: number) {}\n    add = (b: number): number => {\n        return this.a + b;\n    }\n}\nclass Child extends Adder {\n    callAdd(b: number) {\n        return this.add(b);\n    }\n}\n// Demo to show it works\nconst child = new Child(123);\nconsole.log(child.callAdd(123)); // 246\n```\n\nHowever, they do not work with the `super` keyword when you try to override the function in a child class. Properties go on `this`. Since there is only one `this` such functions cannot participate in a call to `super` (`super` only works on prototype members). You can easily get around it by creating a copy of the method before overriding it in the child.\n\n```ts\nclass Adder {\n    constructor(public a: number) {}\n    // This function is now safe to pass around\n    add = (b: number): number => {\n        return this.a + b;\n    }\n}\n\nclass ExtendedAdder extends Adder {\n    // Create a copy of parent before creating our own\n    private superAdd = this.add;\n    // Now create our override\n    add = (b: number): number => {\n        return this.superAdd(b);\n    }\n}\n```\n\n### Tip: Quick object return\n\nSometimes you need a function that just returns a simple object literal. However, something like\n\n```ts\n// WRONG WAY TO DO IT\nvar foo = () => {\n    bar: 123\n};\n```\nis parsed as a *block* containing a *JavaScript Label* by JavaScript runtimes (cause of the JavaScript specification).\n\n>  If that doesn't make sense, don't worry, as you get a nice compiler error from TypeScript saying \"unused label\" anyways. Labels are an old (and mostly unused) JavaScript feature that you can ignore as a modern GOTO (considered bad by experienced developers 🌹)\n\nYou can fix it by surrounding the object literal with `()`:\n\n```ts\n// Correct 🌹\nvar foo = () => ({\n    bar: 123\n});\n```\n"
  },
  {
    "path": "docs/async-await.md",
    "content": "## Async Await\n\n> [A PRO egghead video course that covers the same material](https://egghead.io/courses/async-await-using-typescript)\n\nAs a thought experiment imagine the following: a way to tell the JavaScript runtime to pause the executing of code on the `await` keyword when used on a promise and resume *only* once (and if) the promise returned from the function is settled:\n\n```ts\n// Not actual code. A thought experiment\nasync function foo() {\n    try {\n        var val = await getMeAPromise();\n        console.log(val);\n    }\n    catch(err) {\n        console.log('Error: ', err.message);\n    }\n}\n```\n\nWhen the promise settles execution continues,\n* if it was fulfilled then await will return the value,\n* if it's rejected an error will be thrown synchronously which we can catch.\n\nThis suddenly (and magically) makes asynchronous programming as easy as synchronous programming.  Three things needed for this thought experiment are:\n\n* Ability to *pause function* execution.\n* Ability to *put a value inside* the function.\n* Ability to *throw an exception inside* the function.\n\nThis is exactly what generators allowed us to do! The thought experiment *is actually real* and so is the `async`/`await` implementation in TypeScript / JavaScript. Under the covers it just uses generators.\n\n### Generated JavaScript\n\nYou don't have to understand this, but it's fairly simple if you've [read up on generators][generators]. The function `foo` can be simply wrapped up as follows:\n\n```ts\nconst foo = wrapToReturnPromise(function* () {\n    try {\n        var val = yield getMeAPromise();\n        console.log(val);\n    }\n    catch(err) {\n        console.log('Error: ', err.message);\n    }\n});\n```\n\nwhere the `wrapToReturnPromise` just executes the generator function to get the `generator` and then use `generator.next()`, if the value is a `promise` it would `then`+`catch` the promise and depending upon the result call `generator.next(result)` or `generator.throw(error)`. That's it!\n\n\n\n### Async Await Support in TypeScript\n**Async - Await** has been supported by [TypeScript since version 1.7](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-7.html). Asynchronous functions are prefixed with the *async* keyword; *await* suspends the execution until an asynchronous function return promise is fulfilled and unwraps the value from the *Promise* returned.\nIt was only supported for **target es6** transpiling directly to **ES6 generators**.\n\n**TypeScript 2.1** [added the capability to ES3 and ES5 run-times](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html), meaning you’ll be free to take advantage of it no matter what environment you’re using. It's important to notice that we can use async / await with TypeScript 2.1 and many browsers are supported, of course, having globally added a **polyfill for Promise**.\n\nLet's see this **example** and take a look at this code to figure out how TypeScript async / await **notation** works: \n```ts\nfunction delay(milliseconds: number, count: number): Promise<number> {\n    return new Promise<number>(resolve => {\n            setTimeout(() => {\n                resolve(count);\n            }, milliseconds);\n        });\n}\n\n// async function always returns a Promise\nasync function dramaticWelcome(): Promise<void> {\n    console.log(\"Hello\");\n\n    for (let i = 0; i < 5; i++) {\n        // await is converting Promise<number> into number\n        const count: number = await delay(500, i);\n        console.log(count);\n    }\n\n    console.log(\"World!\");\n}\n\ndramaticWelcome();\n```\n\n**Transpiling to ES6 (--target es6)**\n```js\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n    return new (P || (P = Promise))(function (resolve, reject) {\n        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n        function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n        step((generator = generator.apply(thisArg, _arguments || [])).next());\n    });\n};\nfunction delay(milliseconds, count) {\n    return new Promise(resolve => {\n        setTimeout(() => {\n            resolve(count);\n        }, milliseconds);\n    });\n}\n// async function always returns a Promise\nfunction dramaticWelcome() {\n    return __awaiter(this, void 0, void 0, function* () {\n        console.log(\"Hello\");\n        for (let i = 0; i < 5; i++) {\n            // await is converting Promise<number> into number\n            const count = yield delay(500, i);\n            console.log(count);\n        }\n        console.log(\"World!\");\n    });\n}\ndramaticWelcome();\n```\nYou can see full example [here][asyncawaites6code].\n\n\n**Transpiling to ES5 (--target es5)**\n```js\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n    return new (P || (P = Promise))(function (resolve, reject) {\n        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n        function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n        step((generator = generator.apply(thisArg, _arguments || [])).next());\n    });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n    return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n    function verb(n) { return function (v) { return step([n, v]); }; }\n    function step(op) {\n        if (f) throw new TypeError(\"Generator is already executing.\");\n        while (_) try {\n            if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n            if (y = 0, t) op = [0, t.value];\n            switch (op[0]) {\n                case 0: case 1: t = op; break;\n                case 4: _.label++; return { value: op[1], done: false };\n                case 5: _.label++; y = op[1]; op = [0]; continue;\n                case 7: op = _.ops.pop(); _.trys.pop(); continue;\n                default:\n                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n                    if (t[2]) _.ops.pop();\n                    _.trys.pop(); continue;\n            }\n            op = body.call(thisArg, _);\n        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n    }\n};\nfunction delay(milliseconds, count) {\n    return new Promise(function (resolve) {\n        setTimeout(function () {\n            resolve(count);\n        }, milliseconds);\n    });\n}\n// async function always returns a Promise\nfunction dramaticWelcome() {\n    return __awaiter(this, void 0, void 0, function () {\n        var i, count;\n        return __generator(this, function (_a) {\n            switch (_a.label) {\n                case 0:\n                    console.log(\"Hello\");\n                    i = 0;\n                    _a.label = 1;\n                case 1:\n                    if (!(i < 5)) return [3 /*break*/, 4];\n                    return [4 /*yield*/, delay(500, i)];\n                case 2:\n                    count = _a.sent();\n                    console.log(count);\n                    _a.label = 3;\n                case 3:\n                    i++;\n                    return [3 /*break*/, 1];\n                case 4:\n                    console.log(\"World!\");\n                    return [2 /*return*/];\n            }\n        });\n    });\n}\ndramaticWelcome();\n```\nYou can see full example [here][asyncawaites5code].\n\n\n**Note**: for both target scenarios, we need to make sure our run-time has an ECMAScript-compliant Promise available globally. That might involve grabbing a polyfill for Promise. We also need to make sure that TypeScript knows Promise exists by setting our lib flag to something like \"dom\", \"es2015\" or \"dom\", \"es2015.promise\", \"es5\". \n**We can see what browsers DO have Promise support (native and polyfilled) [here](https://kangax.github.io/compat-table/es6/#test-Promise).**\n\n[generators]:./generators.md\n[asyncawaites5code]:https://cdn.rawgit.com/basarat/typescript-book/705e4496/code/async-await/es5/asyncAwaitES5.js\n[asyncawaites6code]:https://cdn.rawgit.com/basarat/typescript-book/705e4496/code/async-await/es6/asyncAwaitES6.js\n"
  },
  {
    "path": "docs/classes-emit.md",
    "content": "#### What's up with the IIFE\nThe js generated for the class could have been:\n```ts\nfunction Point(x, y) {\n    this.x = x;\n    this.y = y;\n}\nPoint.prototype.add = function (point) {\n    return new Point(this.x + point.x, this.y + point.y);\n};\n```\n\nThe reason it's wrapped in an Immediately-Invoked Function Expression (IIFE) i.e.\n\n```ts\n(function () {\n\n    // BODY\n\n    return Point;\n})();\n```\n\nhas to do with inheritance. It allows TypeScript to capture the base class as a variable `_super` e.g.\n\n```ts\nvar Point3D = (function (_super) {\n    __extends(Point3D, _super);\n    function Point3D(x, y, z) {\n        _super.call(this, x, y);\n        this.z = z;\n    }\n    Point3D.prototype.add = function (point) {\n        var point2D = _super.prototype.add.call(this, point);\n        return new Point3D(point2D.x, point2D.y, this.z + point.z);\n    };\n    return Point3D;\n})(Point);\n```\n\nNotice that the IIFE allows TypeScript to easily capture the base class `Point` in a `_super` variable and that is used consistently in the class body.\n\n### `__extends`\nYou will notice that as soon as you inherit a class TypeScript also generates the following function:\n```ts\nvar __extends = this.__extends || function (d, b) {\n    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n    function __() { this.constructor = d; }\n    __.prototype = b.prototype;\n    d.prototype = new __();\n};\n```\nHere `d` refers to the derived class and `b` refers to the base class. This function does two things:\n\n1. copies the static members of the base class onto the child class i.e. `for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];`\n1. sets up the child class function's prototype to optionally lookup members on the parent's `proto` i.e. effectively `d.prototype.__proto__ = b.prototype`\n\nPeople rarely have trouble understanding 1, but many people struggle with 2. So an explanation is in order.\n\n#### `d.prototype.__proto__ = b.prototype`\n\nAfter having tutored many people about this I find the following explanation to be simplest. First we will explain how the code from `__extends` is equivalent to the simple `d.prototype.__proto__ = b.prototype`, and then why this line in itself is significant. To understand all this you need to know these things:\n\n1. `__proto__`\n1. `prototype`\n1. effect of `new` on `this` inside the called function\n1. effect of `new` on `prototype` and `__proto__`\n\nAll objects in JavaScript contain a `__proto__` member. This member is often not accessible in older browsers (sometimes documentation refers to this magical property as `[[prototype]]`). It has one objective: If a property is not found on an object during lookup (e.g. `obj.property`) then it is looked up at `obj.__proto__.property`. If it is still not found then `obj.__proto__.__proto__.property` till either: *it is found* or *the latest `.__proto__` itself is null*. This explains why JavaScript is said to support *prototypal inheritance* out of the box. This is shown in the following example, which you can run in the chrome console or Node.js:\n\n```ts\nvar foo = {}\n\n// setup on foo as well as foo.__proto__\nfoo.bar = 123;\nfoo.__proto__.bar = 456;\n\nconsole.log(foo.bar); // 123\ndelete foo.bar; // remove from object\nconsole.log(foo.bar); // 456\ndelete foo.__proto__.bar; // remove from foo.__proto__\nconsole.log(foo.bar); // undefined\n```\n\nCool so you understand `__proto__`. Another useful fact is that all `function`s in JavaScript have a property called `prototype` and that it has a member `constructor` pointing back to the function. This is shown below:\n\n```ts\nfunction Foo() { }\nconsole.log(Foo.prototype); // {} i.e. it exists and is not undefined\nconsole.log(Foo.prototype.constructor === Foo); // Has a member called `constructor` pointing back to the function\n```\n\nNow let's look at *effect of `new` on `this` inside the called function*. Basically `this` inside the called function is going to point to the newly created object that will be returned from the function. It's simple to see if you mutate a property on `this` inside the function:\n\n```ts\nfunction Foo() {\n    this.bar = 123;\n}\n\n// call with the new operator\nvar newFoo = new Foo();\nconsole.log(newFoo.bar); // 123\n```\n\nNow the only other thing you need to know is that calling `new` on a function assigns the `prototype` of the function to the `__proto__` of the newly created object that is returned from the function call. Here is the code you can run to completely understand it:\n\n```ts\nfunction Foo() { }\n\nvar foo = new Foo();\n\nconsole.log(foo.__proto__ === Foo.prototype); // True!\n```\n\nThat's it. Now look at the following straight out of `__extends`. I've taken the liberty to number these lines:\n\n```ts\n1  function __() { this.constructor = d; }\n2   __.prototype = b.prototype;\n3   d.prototype = new __();\n```\n\nReading this function in reverse the `d.prototype = new __()` on line 3 effectively means `d.prototype = {__proto__ : __.prototype}` (because of the effect of `new` on `prototype` and `__proto__`), combining it with the previous line (i.e. line 2 `__.prototype = b.prototype;`) you get `d.prototype = {__proto__ : b.prototype}`.\n\nBut wait, we wanted `d.prototype.__proto__` i.e. just the proto changed and maintain the old `d.prototype.constructor`. This is where the significance of the first line (i.e. `function __() { this.constructor = d; }`) comes in. Here we will effectively have `d.prototype = {__proto__ : __.prototype, constructor : d}` (because of the effect of `new` on `this` inside the called function). So, since we restore `d.prototype.constructor`, the only thing we have truly mutated is the `__proto__` hence `d.prototype.__proto__ = b.prototype`.\n\n#### `d.prototype.__proto__ = b.prototype` significance\n\nThe significance is that it allows you to add member functions to a child class and inherit others from the base class. This is demonstrated by the following simple example:\n\n```ts\nfunction Animal() { }\nAnimal.prototype.walk = function () { console.log('walk') };\n\nfunction Bird() { }\nBird.prototype.__proto__ = Animal.prototype;\nBird.prototype.fly = function () { console.log('fly') };\n\nvar bird = new Bird();\nbird.walk();\nbird.fly();\n```\nBasically `bird.fly` will be looked up from `bird.__proto__.fly` (remember that `new` makes the `bird.__proto__` point to `Bird.prototype`) and `bird.walk` (an inherited member) will be looked up from `bird.__proto__.__proto__.walk` (as `bird.__proto__ == Bird.prototype` and `bird.__proto__.__proto__` == `Animal.prototype`).\n"
  },
  {
    "path": "docs/classes.md",
    "content": "### Classes\nThe reason why it's important to have classes in JavaScript as a first class item is that:\n\n1. [Classes offer a useful structural abstraction](./tips/classesAreUseful.md)\n1. Provides a consistent way for developers to use classes instead of every framework (emberjs,reactjs etc) coming up with their own version.\n1. Object Oriented Developers already understand classes.\n\nFinally JavaScript developers can *have `class`*. Here we have a basic class called Point:\n```ts\nclass Point {\n    x: number;\n    y: number;\n    constructor(x: number, y: number) {\n        this.x = x;\n        this.y = y;\n    }\n    add(point: Point) {\n        return new Point(this.x + point.x, this.y + point.y);\n    }\n}\n\nvar p1 = new Point(0, 10);\nvar p2 = new Point(10, 20);\nvar p3 = p1.add(p2); // {x:10,y:30}\n```\nThis class generates the following JavaScript on ES5 emit:\n```ts\nvar Point = (function () {\n    function Point(x, y) {\n        this.x = x;\n        this.y = y;\n    }\n    Point.prototype.add = function (point) {\n        return new Point(this.x + point.x, this.y + point.y);\n    };\n    return Point;\n})();\n```\nThis is a fairly idiomatic traditional JavaScript class pattern now as a first class language construct.\n\n### Inheritance\nClasses in TypeScript (like other languages) support *single* inheritance using the `extends` keyword as shown below:\n\n```ts\nclass Point3D extends Point {\n    z: number;\n    constructor(x: number, y: number, z: number) {\n        super(x, y);\n        this.z = z;\n    }\n    add(point: Point3D) {\n        var point2D = super.add(point);\n        return new Point3D(point2D.x, point2D.y, this.z + point.z);\n    }\n}\n```\nIf you have a constructor in your class then you *must* call the parent constructor from your constructor (TypeScript will point this out to you). This ensures that the stuff that it needs to set on `this` gets set. Followed by the call to `super` you can add any additional stuff you want to do in your constructor (here we add another member `z`).\n\nNote that you override parent member functions easily (here we override `add`) and still use the functionality of the super class in your members (using `super.` syntax).\n\n### Statics\nTypeScript classes support `static` properties that are shared by all instances of the class. A natural place to put (and access) them is on the class itself and that is what TypeScript does:\n\n```ts\nclass Something {\n    static instances = 0;\n    constructor() {\n        Something.instances++;\n    }\n}\n\nvar s1 = new Something();\nvar s2 = new Something();\nconsole.log(Something.instances); // 2\n```\n\nYou can have static members as well as static functions.\n\n### Access Modifiers\nTypeScript supports access modifiers `public`,`private` and `protected` which determine the accessibility of a `class` member as shown below:\n\n| accessible on   | `public` | `protected` | `private` |\n|-----------------|----------|-------------|-----------|\n| class           | yes      | yes         | yes       |\n| class children  | yes      | yes         | no        |\n| class instances | yes      | no          | no        |\n\n\nIf an access modifier is not specified it is implicitly `public` as that matches the *convenient* nature of JavaScript 🌹.\n\nNote that at runtime (in the generated JS) these have no significance but will give you compile time errors if you use them incorrectly. An example of each is shown below:\n\n```ts\nclass FooBase {\n    public x: number;\n    private y: number;\n    protected z: number;\n}\n\n// EFFECT ON INSTANCES\nvar foo = new FooBase();\nfoo.x; // okay\nfoo.y; // ERROR : private\nfoo.z; // ERROR : protected\n\n// EFFECT ON CHILD CLASSES\nclass FooChild extends FooBase {\n    constructor() {\n      super();\n        this.x; // okay\n        this.y; // ERROR: private\n        this.z; // okay\n    }\n}\n```\n\nAs always these modifiers work for both member properties and member functions.\n\n### Abstract\n`abstract` can be thought of as an access modifier. We present it separately because opposed to the previously mentioned modifiers it can be on a `class` as well as any member of the class. Having an `abstract` modifier primarily means that such functionality *cannot be directly invoked* and a child class must provide the functionality.\n\n* `abstract` **classes** cannot be directly instantiated. Instead the user must create some `class` that inherits from the `abstract class`.\n\n```ts\nabstract class FooCommand {}\n\nclass BarCommand extends FooCommand {}\n\nconst fooCommand: FooCommand = new FooCommand(); // Cannot create an instance of an abstract class.\n\nconst barCommand = new BarCommand(); // You can create an instance of a class that inherits from an abstract class.\n```\n\n* `abstract` **members** cannot be directly accessed and a child class must provide the functionality.\n\n```ts\nabstract class FooCommand {\n  abstract execute(): string;\n}\n\nclass BarErrorCommand  extends FooCommand {} // 'BarErrorCommand' needs implement abstract member 'execute'.\n\nclass BarCommand extends FooCommand {\n  execute() {\n    return `Command Bar executed`;\n  }\n}\n\nconst barCommand = new BarCommand();\n\nbarCommand.execute(); // Command Bar executed\n```\n\n### Constructor is optional\n\nThe class does not need to have a constructor. e.g. the following is perfectly fine. \n\n```ts\nclass Foo {}\nvar foo = new Foo();\n```\n\n### Define using constructor\n\nHaving a member in a class and initializing it like below:\n\n```ts\nclass Foo {\n    x: number;\n    constructor(x:number) {\n        this.x = x;\n    }\n}\n```\nis such a common pattern that TypeScript provides a shorthand where you can prefix the member with an *access modifier* and it is automatically declared on the class and copied from the constructor. So the previous example can be re-written as (notice `public x:number`):\n\n```ts\nclass Foo {\n    constructor(public x:number) {\n    }\n}\n```\n\n### Property initializer\nThis is a nifty feature supported by TypeScript (from ES7 actually). You can initialize any member of the class outside the class constructor, useful to provide default (notice `members = []`)\n\n```ts\nclass Foo {\n    members = [];  // Initialize directly\n    add(x) {\n        this.members.push(x);\n    }\n}\n```\n"
  },
  {
    "path": "docs/compiler/ast-tip-children.md",
    "content": "### AST Tip: Visit Children\n\nThere is a utility function `ts.forEachChild` that allows you to visit all the child nodes of any Node in the AST.\n\nHere is simplified snippet of the source code to demonstrate how it functions:\n\n```ts\n\nexport function forEachChild<T>(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T {\n        if (!node) {\n            return;\n        }\n        switch (node.kind) {\n            case SyntaxKind.BinaryExpression:\n                return visitNode(cbNode, (<BinaryExpression>node).left) ||\n                    visitNode(cbNode, (<BinaryExpression>node).operatorToken) ||\n                    visitNode(cbNode, (<BinaryExpression>node).right);\n            case SyntaxKind.IfStatement:\n                return visitNode(cbNode, (<IfStatement>node).expression) ||\n                    visitNode(cbNode, (<IfStatement>node).thenStatement) ||\n                    visitNode(cbNode, (<IfStatement>node).elseStatement);\n\n            // .... lots more\n```\n\nBasically, it checks `node.kind` and based on that assumes an interface offered by the `node` and calls the `cbNode` on the children. However, note that this function doesn't call `visitNode` for *all* children (e.g. SyntaxKind.SemicolonToken). If you want *all* the children of a node in the AST just call `.getChildren` member function of the `Node`.\n\nE.g. here is a function that prints the verbose `AST` of a node:\n\n```ts\nfunction printAllChildren(node: ts.Node, depth = 0) {\n    console.log(new Array(depth+1).join('----'), ts.syntaxKindToName(node.kind), node.pos, node.end);\n    depth++;\n    node.getChildren().forEach(c=> printAllChildren(c, depth));\n}\n```\n\nWe will see a sample usage of this function when we discuss the parser further.\n"
  },
  {
    "path": "docs/compiler/ast-tip-syntaxkind.md",
    "content": "### AST Tip: SyntaxKind\n\n`SyntaxKind` is defined as a `const enum`, here is a sample:\n\n```ts\nexport const enum SyntaxKind {\n    Unknown,\n    EndOfFileToken,\n    SingleLineCommentTrivia,\n    // ... LOTS more\n```\n\nIt's a `const enum` (a concept [we covered previously](../enums.md)) so that it gets *inlined* (e.g. `ts.SyntaxKind.EndOfFileToken` becomes `1`) and we don't get a dereferencing cost when working with the AST. However, the compiler is compiled with `--preserveConstEnums` compiler flag so that the enum *is still available at runtime*. So in JavaScript you can use `ts.SyntaxKind.EndOfFileToken` if you want. Additionally you can convert these enum members to display strings using the following function:\n\n```ts\nexport function syntaxKindToName(kind: ts.SyntaxKind) {\n    return (<any>ts).SyntaxKind[kind];\n}\n```\n"
  },
  {
    "path": "docs/compiler/ast-trivia.md",
    "content": "### Trivia\nTrivia (called that because it's `trivial`) represent the parts of the source text that are largely insignificant for normal understanding of the code. For example; whitespace, comments, and even conflict markers. Trivia is *not stored* in the AST (to keep it lightweight). However, it can be fetched *on demand* using a few `ts.*` APIs. \n\nBefore we show them you need to understand the following:\n\n#### Trivia Ownership\nIn General:\n* A token owns any trivia after it on the *same* line *upto* the next token.\n* Any comment *after that line* is associated with the following token.\n\nFor leading and ending comments in a file:\n* The first token in the source file gets all the initial trivia.\n* The last sequence of trivia in the file is tacked onto the end-of-file token, which otherwise has zero width.\n\n#### Trivia APIs\nFor most basic uses, comments are the \"interesting\" trivia. The comments that belong to a Node can be fetched through the following functions:\n\nFunction | Description\n---------|------------\n`ts.getLeadingCommentRanges` | Given the source text and position within that text, returns ranges of comments between the first line break following the given position and the token itself (probably most useful with `ts.Node.getFullStart`).\n`ts.getTrailingCommentRanges` | Given the source text and position within that text, returns ranges of comments until the first line break following the given position (probably most useful with `ts.Node.getEnd`).\n\nAs an example, imagine this portion of a source file:\n\n```ts\ndebugger;/*hello*/\n    //bye\n  /*hi*/    function\n```\n\n`getLeadingCommentRanges` for the `function` will only return the last 2 comments `//bye` and `/*hi*/`.\n\nAppropriately, calling `getTrailingCommentRanges` on the end of the debugger statement will extract the `/*hello*/` comment.\n\n#### Token Start/Full Start\nNodes have what is called a \"token start\" and a \"full start\".\n\n* Token Start: the more natural version, which is the position in file where the text of a token begins\n* Full Start: the point at which the scanner began scanning since the last significant token\n\nAST nodes have an API for `getStart` and `getFullStart`. In the following example:\n\n```ts\ndebugger;/*hello*/\n    //bye\n  /*hi*/    function\n```\nfor `function` the token start is at `function` whereas *full* start is at `/*hello*/`. Note that full start even includes the trivia that would otherwise be owned by the previous node.\n"
  },
  {
    "path": "docs/compiler/ast.md",
    "content": "## Node\nThe basic building block of the Abstract Syntax Tree (AST). In general a `Node` represents non-terminals in the language grammar; however, some terminals are kept in the tree such as identifiers and literals.\n\nTwo key things make up an AST node's documentation. The node's `SyntaxKind` which identifies its type within the AST, and its `interface`, the API the node provides when instantiated into the AST.\n\nHere are a few key `interface Node` members:\n* `TextRange` members that identify the node's `start` and `end` in the source file.\n* `parent?: Node` the parent of the node in the AST.\n\nThere are other additional members for `Node` flags and modifiers etc. that you can lookup by searching `interface Node` in the source code but the ones we mentioned are vital for node traversal.\n\n## SourceFile\n\n* `SyntaxKind.SourceFile`\n* `interface SourceFile`.\n\nEach `SourceFile` is a top-level AST node that is contained in the `Program`.\n"
  },
  {
    "path": "docs/compiler/binder-container.md",
    "content": "### Container\n\nAn AST node can be a container. This determines the kinds of `SymbolTables` the Node and associated Symbol will have. Container is an abstract concept (i.e. has no associated data structure). The concept is driven by a few things, one being the `ContainerFlags` enum. The function `getContainerFlags` (in `binder.ts`) drives this flag and is presented below:\n\n```ts\nfunction getContainerFlags(node: Node): ContainerFlags {\n    switch (node.kind) {\n        case SyntaxKind.ClassExpression:\n        case SyntaxKind.ClassDeclaration:\n        case SyntaxKind.InterfaceDeclaration:\n        case SyntaxKind.EnumDeclaration:\n        case SyntaxKind.TypeLiteral:\n        case SyntaxKind.ObjectLiteralExpression:\n            return ContainerFlags.IsContainer;\n\n        case SyntaxKind.CallSignature:\n        case SyntaxKind.ConstructSignature:\n        case SyntaxKind.IndexSignature:\n        case SyntaxKind.MethodDeclaration:\n        case SyntaxKind.MethodSignature:\n        case SyntaxKind.FunctionDeclaration:\n        case SyntaxKind.Constructor:\n        case SyntaxKind.GetAccessor:\n        case SyntaxKind.SetAccessor:\n        case SyntaxKind.FunctionType:\n        case SyntaxKind.ConstructorType:\n        case SyntaxKind.FunctionExpression:\n        case SyntaxKind.ArrowFunction:\n        case SyntaxKind.ModuleDeclaration:\n        case SyntaxKind.SourceFile:\n        case SyntaxKind.TypeAliasDeclaration:\n            return ContainerFlags.IsContainerWithLocals;\n\n        case SyntaxKind.CatchClause:\n        case SyntaxKind.ForStatement:\n        case SyntaxKind.ForInStatement:\n        case SyntaxKind.ForOfStatement:\n        case SyntaxKind.CaseBlock:\n            return ContainerFlags.IsBlockScopedContainer;\n\n        case SyntaxKind.Block:\n            // do not treat blocks directly inside a function as a block-scoped-container.\n            // Locals that reside in this block should go to the function locals. Otherwise 'x'\n            // would not appear to be a redeclaration of a block scoped local in the following\n            // example:\n            //\n            //      function foo() {\n            //          var x;\n            //          let x;\n            //      }\n            //\n            // If we placed 'var x' into the function locals and 'let x' into the locals of\n            // the block, then there would be no collision.\n            //\n            // By not creating a new block-scoped-container here, we ensure that both 'var x'\n            // and 'let x' go into the Function-container's locals, and we do get a collision\n            // conflict.\n            return isFunctionLike(node.parent) ? ContainerFlags.None : ContainerFlags.IsBlockScopedContainer;\n    }\n\n    return ContainerFlags.None;\n}\n```\n\nIt is *only* invoked from the binder's `bindChildren` function which sets up a node as a `container` and/or a `blockScopedContainer` depending upon the evaluation of the `getContainerFlags` function. The function `bindChildren` is presented below:\n\n```ts\n// All container nodes are kept on a linked list in declaration order. This list is used by\n// the getLocalNameOfContainer function in the type checker to validate that the local name\n// used for a container is unique.\nfunction bindChildren(node: Node) {\n    // Before we recurse into a node's children, we first save the existing parent, container\n    // and block-container.  Then after we pop out of processing the children, we restore\n    // these saved values.\n    let saveParent = parent;\n    let saveContainer = container;\n    let savedBlockScopeContainer = blockScopeContainer;\n\n    // This node will now be set as the parent of all of its children as we recurse into them.\n    parent = node;\n\n    // Depending on what kind of node this is, we may have to adjust the current container\n    // and block-container.   If the current node is a container, then it is automatically\n    // considered the current block-container as well.  Also, for containers that we know\n    // may contain locals, we proactively initialize the .locals field. We do this because\n    // it's highly likely that the .locals will be needed to place some child in (for example,\n    // a parameter, or variable declaration).\n    //\n    // However, we do not proactively create the .locals for block-containers because it's\n    // totally normal and common for block-containers to never actually have a block-scoped\n    // variable in them.  We don't want to end up allocating an object for every 'block' we\n    // run into when most of them won't be necessary.\n    //\n    // Finally, if this is a block-container, then we clear out any existing .locals object\n    // it may contain within it.  This happens in incremental scenarios.  Because we can be\n    // reusing a node from a previous compilation, that node may have had 'locals' created\n    // for it.  We must clear this so we don't accidentally move any stale data forward from\n    // a previous compilation.\n    let containerFlags = getContainerFlags(node);\n    if (containerFlags & ContainerFlags.IsContainer) {\n        container = blockScopeContainer = node;\n\n        if (containerFlags & ContainerFlags.HasLocals) {\n            container.locals = {};\n        }\n\n        addToContainerChain(container);\n    }\n\n    else if (containerFlags & ContainerFlags.IsBlockScopedContainer) {\n        blockScopeContainer = node;\n        blockScopeContainer.locals = undefined;\n    }\n\n    forEachChild(node, bind);\n\n    container = saveContainer;\n    parent = saveParent;\n    blockScopeContainer = savedBlockScopeContainer;\n}\n```\n\nAs you might recall from the section on binder functions : `bindChildren` is called from the `bind` function. So we have the recursive binding setup : `bind` calls `bindChildren` calls `bind` for each child.\n"
  },
  {
    "path": "docs/compiler/binder-declarations.md",
    "content": "### Symbols and Declarations\nLinking between a `node` and a `symbol` is performed by a few functions. One function that is used to bind the `SourceFile` node to the source file Symbol (in case of an external module) is the `addDeclarationToSymbol` function\n\nNote : the `Symbol` for an external module source file is setup as `flags : SymbolFlags.ValueModule` and `name: '\"' + removeFileExtension(file.fileName) + '\"'`).\n\n```ts\nfunction addDeclarationToSymbol(symbol: Symbol, node: Declaration, symbolFlags: SymbolFlags) {\n    symbol.flags |= symbolFlags;\n\n    node.symbol = symbol;\n\n    if (!symbol.declarations) {\n        symbol.declarations = [];\n    }\n    symbol.declarations.push(node);\n\n    if (symbolFlags & SymbolFlags.HasExports && !symbol.exports) {\n        symbol.exports = {};\n    }\n\n    if (symbolFlags & SymbolFlags.HasMembers && !symbol.members) {\n        symbol.members = {};\n    }\n\n    if (symbolFlags & SymbolFlags.Value && !symbol.valueDeclaration) {\n        symbol.valueDeclaration = node;\n    }\n}\n```\n\nThe important linking portions:\n* Creates a link to the Symbol from the AST node (`node.symbol`).\n* Adds the node as *one of* the declarations of the Symbol (`symbol.declarations`).\n\n#### Declaration\nDeclaration is just a `node` with an optional name. In `types.ts`\n\n```ts\ninterface Declaration extends Node {\n    _declarationBrand: any;\n    name?: DeclarationName;\n}\n```\n"
  },
  {
    "path": "docs/compiler/binder-diagnostics.md",
    "content": "### Binder Error Reporting\n\nBinding errors are added to the sourceFile's list of `bindDiagnostics`.\n\nAn example error detected during binding is the use of `eval` or `arguments` as a variable name in `use strict` scenario. The relevant code is presented in its entirety below (`checkStrictModeEvalOrArguments` is called from multiple places, call stacks originating from `bindWorker` which calls different functions for different node `SyntaxKind`):\n\n```ts\nfunction checkStrictModeEvalOrArguments(contextNode: Node, name: Node) {\n    if (name && name.kind === SyntaxKind.Identifier) {\n        let identifier = <Identifier>name;\n        if (isEvalOrArgumentsIdentifier(identifier)) {\n            // We check first if the name is inside class declaration or class expression; if so give explicit message\n            // otherwise report generic error message.\n            let span = getErrorSpanForNode(file, name);\n            file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length,\n                getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text));\n        }\n    }\n}\n\nfunction isEvalOrArgumentsIdentifier(node: Node): boolean {\n    return node.kind === SyntaxKind.Identifier &&\n        ((<Identifier>node).text === \"eval\" || (<Identifier>node).text === \"arguments\");\n}\n\nfunction getStrictModeEvalOrArgumentsMessage(node: Node) {\n    // Provide specialized messages to help the user understand why we think they're in\n    // strict mode.\n    if (getContainingClass(node)) {\n        return Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;\n    }\n\n    if (file.externalModuleIndicator) {\n        return Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;\n    }\n\n    return Diagnostics.Invalid_use_of_0_in_strict_mode;\n}\n```\n"
  },
  {
    "path": "docs/compiler/binder-functions.md",
    "content": "### Binder function\nTwo critical binder functions are `bindSourceFile` and `mergeSymbolTable`. We will take a look at these next.\n\n#### `bindSourceFile`\nBasically checks if `file.locals` is defined, if not it hands over to (a local function) `bind`.\n\nNote: `locals` is defined on `Node` and is of type `SymbolTable`. Note that `SourceFile` is also a `Node` (in fact a root node in the AST).\n\nTIP: local functions are used heavily within the TypeScript compiler. A local function very likely uses variables from the parent function (captured by closure). In the case of `bind` (a local function within `bindSourceFile`) it (or a function it calls) will setup the `symbolCount` and `classifiableNames` among others, that are then stored on the returned `SourceFile`.\n\n#### `bind`\nBind takes any `Node` (not just `SourceFile`). First thing it does is assign the `node.parent` (if `parent` variable has been setup ... which again is something the binder does during its processing within the `bindChildren` function), then hands off to `bindWorker` which does the *heavy* lifting. Finally it calls `bindChildren` (a function that simply stores the binder state e.g. current `parent` within its function local vars, then calls `bind` on each child, and then restores the binder state). Now let's look at `bindWorker` which is the more interesting function.\n\n#### `bindWorker`\nThis function switches on `node.kind` (of type `SyntaxKind`) and delegates work to the appropriate `bindFoo` function (also defined within `binder.ts`). For example if the `node` is a `SourceFile` it calls (eventually and only if its an external file module) `bindAnonymousDeclaration`\n\n#### `bindFoo` functions\nThere are a few patterns common to `bindFoo` functions as well as some utility functions that these use. One function that is almost always used is the `createSymbol` function. It is presented in its entirety below:\n\n```ts\nfunction createSymbol(flags: SymbolFlags, name: string): Symbol {\n    symbolCount++;\n    return new Symbol(flags, name);\n}\n```\nAs you can see it is simply keeping the `symbolCount` (a local to `bindSourceFile`) up to date and creating the symbol with the specified parameters.\n"
  },
  {
    "path": "docs/compiler/binder-symbolflags.md",
    "content": "### SymbolFlags\nSymbols have `SymbolFlags`. Below we have them in their verbatim, as of TypeScript 2.2\n\n```ts\n    export const enum SymbolFlags {\n        None                    = 0,\n        FunctionScopedVariable  = 1 << 0,   // Variable (var) or parameter\n        BlockScopedVariable     = 1 << 1,   // A block-scoped variable (let or const)\n        Property                = 1 << 2,   // Property or enum member\n        EnumMember              = 1 << 3,   // Enum member\n        Function                = 1 << 4,   // Function\n        Class                   = 1 << 5,   // Class\n        Interface               = 1 << 6,   // Interface\n        ConstEnum               = 1 << 7,   // Const enum\n        RegularEnum             = 1 << 8,   // Enum\n        ValueModule             = 1 << 9,   // Instantiated module\n        NamespaceModule         = 1 << 10,  // Uninstantiated module\n        TypeLiteral             = 1 << 11,  // Type Literal or mapped type\n        ObjectLiteral           = 1 << 12,  // Object Literal\n        Method                  = 1 << 13,  // Method\n        Constructor             = 1 << 14,  // Constructor\n        GetAccessor             = 1 << 15,  // Get accessor\n        SetAccessor             = 1 << 16,  // Set accessor\n        Signature               = 1 << 17,  // Call, construct, or index signature\n        TypeParameter           = 1 << 18,  // Type parameter\n        TypeAlias               = 1 << 19,  // Type alias\n        ExportValue             = 1 << 20,  // Exported value marker (see comment in declareModuleMember in binder)\n        ExportType              = 1 << 21,  // Exported type marker (see comment in declareModuleMember in binder)\n        ExportNamespace         = 1 << 22,  // Exported namespace marker (see comment in declareModuleMember in binder)\n        Alias                   = 1 << 23,  // An alias for another symbol (see comment in isAliasSymbolDeclaration in checker)\n        Prototype               = 1 << 24,  // Prototype property (no source representation)\n        ExportStar              = 1 << 25,  // Export * declaration\n        Optional                = 1 << 26,  // Optional property\n        Transient               = 1 << 27,  // Transient symbol (created during type check)\n\n        Enum = RegularEnum | ConstEnum,\n        Variable = FunctionScopedVariable | BlockScopedVariable,\n        Value = Variable | Property | EnumMember | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor,\n        Type = Class | Interface | Enum | EnumMember | TypeLiteral | ObjectLiteral | TypeParameter | TypeAlias,\n        Namespace = ValueModule | NamespaceModule | Enum,\n        Module = ValueModule | NamespaceModule,\n        Accessor = GetAccessor | SetAccessor,\n\n        // Variables can be redeclared, but can not redeclare a block-scoped declaration with the\n        // same name, or any other value that is not a variable, e.g. ValueModule or Class\n        FunctionScopedVariableExcludes = Value & ~FunctionScopedVariable,\n\n        // Block-scoped declarations are not allowed to be re-declared\n        // they can not merge with anything in the value space\n        BlockScopedVariableExcludes = Value,\n\n        ParameterExcludes = Value,\n        PropertyExcludes = None,\n        EnumMemberExcludes = Value | Type,\n        FunctionExcludes = Value & ~(Function | ValueModule),\n        ClassExcludes = (Value | Type) & ~(ValueModule | Interface), // class-interface mergability done in checker.ts\n        InterfaceExcludes = Type & ~(Interface | Class),\n        RegularEnumExcludes = (Value | Type) & ~(RegularEnum | ValueModule), // regular enums merge only with regular enums and modules\n        ConstEnumExcludes = (Value | Type) & ~ConstEnum, // const enums merge only with const enums\n        ValueModuleExcludes = Value & ~(Function | Class | RegularEnum | ValueModule),\n        NamespaceModuleExcludes = 0,\n        MethodExcludes = Value & ~Method,\n        GetAccessorExcludes = Value & ~SetAccessor,\n        SetAccessorExcludes = Value & ~GetAccessor,\n        TypeParameterExcludes = Type & ~TypeParameter,\n        TypeAliasExcludes = Type,\n        AliasExcludes = Alias,\n\n        ModuleMember = Variable | Function | Class | Interface | Enum | Module | TypeAlias | Alias,\n\n        ExportHasLocal = Function | Class | Enum | ValueModule,\n\n        HasExports = Class | Enum | Module,\n        HasMembers = Class | Interface | TypeLiteral | ObjectLiteral,\n\n        BlockScoped = BlockScopedVariable | Class | Enum,\n\n        PropertyOrAccessor = Property | Accessor,\n        Export = ExportNamespace | ExportType | ExportValue,\n\n        ClassMember = Method | Accessor | Property,\n\n        /* @internal */\n        // The set of things we consider semantically classifiable.  Used to speed up the LS during\n        // classification.\n        Classifiable = Class | Enum | TypeAlias | Interface | TypeParameter | Module,\n    }\n```\n\n#### ValueModule\n`ValueModule // Instantiated module` is the SymbolFlag used for `SourceFile` if it an external module.\n"
  },
  {
    "path": "docs/compiler/binder-symboltable.md",
    "content": "### SymbolTable\n\nSymbolTable is implemented as a simple HashMap. Here is the interface (`types.ts`):\n\n```ts\ninterface SymbolTable {\n    [index: string]: Symbol;\n}\n```\n\nSymbolTables are initialized by binding. There are a few SymbolTables used by the compiler:\n\nOn `Node`:\n```ts\nlocals?: SymbolTable;                   // Locals associated with node\n```\n\nOn `Symbol`:\n\n```ts\nmembers?: SymbolTable;                  // Class, interface or literal instance members\nexports?: SymbolTable;                  // Module exports\n```\n\nNote: We saw `locals` getting initialized (to `{}`) by `bindChildren` based on `ContainerFlags`.\n\n#### SymbolTable population\nSymbolTables are populated with `Symbols` primarily by a call to `declareSymbol`. This function is presented below in entirety:\n\n```ts\n/**\n * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.\n * @param symbolTable - The symbol table which node will be added to.\n * @param parent - node's parent declaration.\n * @param node - The declaration to be added to the symbol table\n * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)\n * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.\n */\nfunction declareSymbol(symbolTable: SymbolTable, parent: Symbol, node: Declaration, includes: SymbolFlags, excludes: SymbolFlags): Symbol {\n    Debug.assert(!hasDynamicName(node));\n\n    // The exported symbol for an export default function/class node is always named \"default\"\n    let name = node.flags & NodeFlags.Default && parent ? \"default\" : getDeclarationName(node);\n\n    let symbol: Symbol;\n    if (name !== undefined) {\n\n        // Check and see if the symbol table already has a symbol with this name.  If not,\n        // create a new symbol with this name and add it to the table.  Note that we don't\n        // give the new symbol any flags *yet*.  This ensures that it will not conflict\n        // with the 'excludes' flags we pass in.\n        //\n        // If we do get an existing symbol, see if it conflicts with the new symbol we're\n        // creating.  For example, a 'var' symbol and a 'class' symbol will conflict within\n        // the same symbol table.  If we have a conflict, report the issue on each\n        // declaration we have for this symbol, and then create a new symbol for this\n        // declaration.\n        //\n        // If we created a new symbol, either because we didn't have a symbol with this name\n        // in the symbol table, or we conflicted with an existing symbol, then just add this\n        // node as the sole declaration of the new symbol.\n        //\n        // Otherwise, we'll be merging into a compatible existing symbol (for example when\n        // you have multiple 'vars' with the same name in the same container).  In this case\n        // just add this node into the declarations list of the symbol.\n        symbol = hasProperty(symbolTable, name)\n            ? symbolTable[name]\n            : (symbolTable[name] = createSymbol(SymbolFlags.None, name));\n\n        if (name && (includes & SymbolFlags.Classifiable)) {\n            classifiableNames[name] = name;\n        }\n\n        if (symbol.flags & excludes) {\n            if (node.name) {\n                node.name.parent = node;\n            }\n\n            // Report errors every position with duplicate declaration\n            // Report errors on previous encountered declarations\n            let message = symbol.flags & SymbolFlags.BlockScopedVariable\n                ? Diagnostics.Cannot_redeclare_block_scoped_variable_0\n                : Diagnostics.Duplicate_identifier_0;\n            forEach(symbol.declarations, declaration => {\n                file.bindDiagnostics.push(createDiagnosticForNode(declaration.name || declaration, message, getDisplayName(declaration)));\n            });\n            file.bindDiagnostics.push(createDiagnosticForNode(node.name || node, message, getDisplayName(node)));\n\n            symbol = createSymbol(SymbolFlags.None, name);\n        }\n    }\n    else {\n        symbol = createSymbol(SymbolFlags.None, \"__missing\");\n    }\n\n    addDeclarationToSymbol(symbol, node, includes);\n    symbol.parent = parent;\n\n    return symbol;\n}\n```\n\nWhich SymbolTable is populated is driven by the first argument to this function. e.g. when adding a declaration to a *container* of kind `SyntaxKind.ClassDeclaration` or `SyntaxKind.ClassExpression` the function `declareClassMember` will get called which has the following code:\n\n```ts\nfunction declareClassMember(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) {\n    return node.flags & NodeFlags.Static\n        ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)\n        : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);\n}\n```\n"
  },
  {
    "path": "docs/compiler/binder.md",
    "content": "## Binder\nMost JavaScript transpilers out there are simpler than TypeScript because they provide little in the way of code analysis. The typical JavaScript transpilers only have the following flow:\n\n```ts\nSourceCode ~~Scanner~~> Tokens ~~Parser~~> AST ~~Emitter~~> JavaScript\n```\n\nWhile the above architecture is true as a simplified understanding of TypeScript js generation, a key feature of TypeScript is its *Semantic* system. In order to assist type checking (performed by the `checker`), the `binder` (in `binder.ts`) is used to connect the various parts of the source code into a coherent type system that can then be used by the `checker`. The main responsibility of the binder is to create _Symbols_.\n\n### Symbol\nSymbols connect declaration nodes in the AST to other declarations contributing to the same entity. Symbols are the basic building blocks of the Semantic system. The symbol constructor is defined in `core.ts` (and `binder` actually uses the `objectAllocator.getSymbolConstructor` to get its hands on it). Here is the symbol constructor:\n\n```ts\nfunction Symbol(flags: SymbolFlags, name: string) {\n    this.flags = flags;\n    this.name = name;\n    this.declarations = undefined;\n}\n```\n\n`SymbolFlags` is a flag enum and is really used to identify additional classifications of the symbol (e.g. variable scope flags `FunctionScopedVariable` or `BlockScopedVariable` among others)\n\n### Usage by Checker\nThe `binder` is actually used internally by the type `checker` which in turn is used by the `program`. The simplified call stack looks like:\n```\nprogram.getTypeChecker ->\n    ts.createTypeChecker (in checker)->\n        initializeTypeChecker (in checker) ->\n            for each SourceFile `ts.bindSourceFile` (in binder)\n            // followed by\n            for each SourceFile `ts.mergeSymbolTable` (in checker)\n```\nThe unit of work for the binder is a SourceFile. The `binder.ts` is driven by `checker.ts`.\n"
  },
  {
    "path": "docs/compiler/checker-diagnostics.md",
    "content": "### Checker error reporting\nThe checker uses the local `error` function to report errors. Here is the function:\n\n```ts\nfunction error(location: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): void {\n    let diagnostic = location\n        ? createDiagnosticForNode(location, message, arg0, arg1, arg2)\n        : createCompilerDiagnostic(message, arg0, arg1, arg2);\n    diagnostics.add(diagnostic);\n}\n```\n"
  },
  {
    "path": "docs/compiler/checker-global.md",
    "content": "### Global Namespace Merging\nWithin `initializeTypeChecker` the following code exists:\n\n```ts\n// Initialize global symbol table\nforEach(host.getSourceFiles(), file => {\n    if (!isExternalModule(file)) {\n        mergeSymbolTable(globals, file.locals);\n    }\n});\n```\n\nWhich basically merges all the `global` symbols into the `let globals: SymbolTable = {};` (in `createTypeChecker`) SymbolTable. `mergeSymbolTable` primarily calls `mergeSymbol`.\n"
  },
  {
    "path": "docs/compiler/checker.md",
    "content": "## Checker\nLike we mentioned before *checker* is the thing that makes TypeScript uniquely more powerful than *just another JavaScript transpiler*. The checker is located in `checker.ts` and at this moment it is 23k+ lines of TypeScript (largest part of the compiler).\n\n### Usage by Program\nThe `checker` is initialized by `program`. The following is a sampling of the call stack (we showed the same one when looking at `binder`):\n\n```\nprogram.getTypeChecker ->\n    ts.createTypeChecker (in checker)->\n        initializeTypeChecker (in checker) ->\n            for each SourceFile `ts.bindSourceFile` (in binder)\n            // followed by\n            for each SourceFile `ts.mergeSymbolTable` (in checker)\n```\n\n### Association with Emitter\nTrue type checking happens once a call is made to `getDiagnostics`. This function is called e.g. once a request is made to `Program.emit`, in which case the checker returns an `EmitResolver` (program calls the checkers `getEmitResolver` function) which is just a set of functions local to `createTypeChecker`. We will mention this again when we look at the emitter.\n\nHere is the call stack right down to `checkSourceFile` (a function local to `createTypeChecker`).\n\n```\nprogram.emit ->\n    emitWorker (program local) ->\n        createTypeChecker.getEmitResolver ->\n            // First call the following functions local to createTypeChecker\n            call getDiagnostics ->\n                getDiagnosticsWorker ->\n                    checkSourceFile\n\n            // then\n            return resolver\n            (already initialized in createTypeChecker using a call to local createResolver())\n```\n"
  },
  {
    "path": "docs/compiler/contributing.md",
    "content": "## Contributing\n\nTypeScript is [OSS and on GitHub](https://github.com/Microsoft/TypeScript) and the team welcomes community input.\n\n### Setup\nSuper easy:\n\n```bash\ngit clone https://github.com/Microsoft/TypeScript.git\ncd TypeScript\nnpm install -g jake\nnpm install\n```\n\n### Setup Fork\nYou would obviously need to setup Microsoft/TypeScript as an `upstream` remote and your own *fork* (use the GitHub *fork* button) as `origin`:\n\n```bash\ngit remote rm origin\ngit remote rm upstream\ngit remote add upstream https://github.com/Microsoft/TypeScript.git\ngit remote add origin https://github.com/basarat/TypeScript.git\n```\nAdditionally I like to work off branches like `bas/` to have it show up cleaner in the branch listings.\n\n### Running Tests\nThere are lots of `test` and `build` options in their JakeFile. You can run *all* tests with `jake runtests`\n\n### Baselines\nBaselines are used to manage if there are any changes in the *expected* output of the TypeScript compiler. Baselines are located in `tests/baselines`.\n\n* Reference (*expected*) baselines: `tests/baselines/reference`\n* Generated (*in this test run*) baselines : `tests/baselines/local` (this folder is in **.gitignore**)\n\n> If there are any differences between these folders tests will fail. You can diff the two folders with tools like BeyondCompare or KDiff3.\n\nIf you think these changes in generated files are valid then accept baselines using `jake baseline-accept`. The changes to `reference` baselines will now show as a git diff you can commit.\n\n> Note that if you don't run *all* tests then use `jake baseline-accept[soft]` which will only copy over the new files and not delete the whole `reference` directory.\n\n### Test Categories\n\nThere are different categories for different scenarios and even different test infrastructures. Here are a few of these explained.\n\n#### Compiler Tests\n\nThese ensure that compiling a file :\n\n* generates errors as expected\n* generated JS as expected\n* types are identified as expected\n* symbols are identified as expected\n\nThese expectations are validated using the baselines infrastructure.\n\n##### Creating a Compiler Test\nTest can be created by adding a new file `yourtest.ts` to `tests/cases/compiler`. As soon as you do so and run the tests you should get baseline failure. Accept these baselines (to get them to show up in git), and tweak them to be what you *expect* them to be ... now get the tests to pass.\n\nRun all of these in isolation using `jake runtests tests=compiler`, or just your new file using `jake runtests tests=compiler/yourtest`\n\nI will even often do `jake runtests tests=compiler/yourtest || jake baseline-accept[soft]` and get the diff in `git`.\n\n### Debugging Tests\n\n`jake runtests-browser tests=theNameOfYourTest` and debugging in-browser usually works pretty well.\n\n### More \n* An article by Remo : https://dev.to/remojansen/learn-how-to-contribute-to-the-typescript-compiler-on-github-through-a-real-world-example-4df0 🌹\n"
  },
  {
    "path": "docs/compiler/emitter-functions.md",
    "content": "### `emitFiles`\nDefined in `emitter.ts` here is the function signature:\n```ts\n// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature\nexport function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile?: SourceFile): EmitResult {\n```\n\n`EmitHost` is just a simplified (as in narrowed down) version of `CompilerHost` (and is at runtime actually a `CompilerHost` for many use cases).\n\nThe most interesting call stack from `emitFiles` is the following:\n\n```\nemitFiles ->\n    emitFile(jsFilePath, targetSourceFile) ->\n        emitJavaScript(jsFilePath, targetSourceFile);\n```\n\n### `emitJavaScript`\nThere is a lot of good comments in this function so we present it below :\n\n```ts\nfunction emitJavaScript(jsFilePath: string, root?: SourceFile) {\n    let writer = createTextWriter(newLine);\n    let write = writer.write;\n    let writeTextOfNode = writer.writeTextOfNode;\n    let writeLine = writer.writeLine;\n    let increaseIndent = writer.increaseIndent;\n    let decreaseIndent = writer.decreaseIndent;\n\n    let currentSourceFile: SourceFile;\n    // name of an exporter function if file is a System external module\n    // System.register([...], function (<exporter>) {...})\n    // exporting in System modules looks like:\n    // export var x; ... x = 1\n    // =>\n    // var x;... exporter(\"x\", x = 1)\n    let exportFunctionForFile: string;\n\n    let generatedNameSet: Map<string> = {};\n    let nodeToGeneratedName: string[] = [];\n    let computedPropertyNamesToGeneratedNames: string[];\n\n    let extendsEmitted = false;\n    let decorateEmitted = false;\n    let paramEmitted = false;\n    let awaiterEmitted = false;\n    let tempFlags = 0;\n    let tempVariables: Identifier[];\n    let tempParameters: Identifier[];\n    let externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[];\n    let exportSpecifiers: Map<ExportSpecifier[]>;\n    let exportEquals: ExportAssignment;\n    let hasExportStars: boolean;\n\n    /** Write emitted output to disk */\n    let writeEmittedFiles = writeJavaScriptFile;\n\n    let detachedCommentsInfo: { nodePos: number; detachedCommentEndPos: number }[];\n\n    let writeComment = writeCommentRange;\n\n    /** Emit a node */\n    let emit = emitNodeWithoutSourceMap;\n\n    /** Called just before starting emit of a node */\n    let emitStart = function (node: Node) { };\n\n    /** Called once the emit of the node is done */\n    let emitEnd = function (node: Node) { };\n\n    /** Emit the text for the given token that comes after startPos\n      * This by default writes the text provided with the given tokenKind\n      * but if optional emitFn callback is provided the text is emitted using the callback instead of default text\n      * @param tokenKind the kind of the token to search and emit\n      * @param startPos the position in the source to start searching for the token\n      * @param emitFn if given will be invoked to emit the text instead of actual token emit */\n    let emitToken = emitTokenText;\n\n    /** Called to before starting the lexical scopes as in function/class in the emitted code because of node\n      * @param scopeDeclaration node that starts the lexical scope\n      * @param scopeName Optional name of this scope instead of deducing one from the declaration node */\n    let scopeEmitStart = function(scopeDeclaration: Node, scopeName?: string) { };\n\n    /** Called after coming out of the scope */\n    let scopeEmitEnd = function() { };\n\n    /** Sourcemap data that will get encoded */\n    let sourceMapData: SourceMapData;\n\n    if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) {\n        initializeEmitterWithSourceMaps();\n    }\n\n    if (root) {\n        // Do not call emit directly. It does not set the currentSourceFile.\n        emitSourceFile(root);\n    }\n    else {\n        forEach(host.getSourceFiles(), sourceFile => {\n            if (!isExternalModuleOrDeclarationFile(sourceFile)) {\n                emitSourceFile(sourceFile);\n            }\n        });\n    }\n\n    writeLine();\n    writeEmittedFiles(writer.getText(), /*writeByteOrderMark*/ compilerOptions.emitBOM);\n    return;\n\n    /// BUNCH OF LOCAL FUNCTIONS\n}\n```\n\nBasically it sets up a bunch of locals (these functions form the *bulk* of `emitter.ts`) and then hands off to a local function `emitSourceFile` which kicks off the emit. The `emitSourceFile` function just sets up the `currentSourceFile` and in turn hands off to a local `emit` function.\n\n```ts\nfunction emitSourceFile(sourceFile: SourceFile): void {\n    currentSourceFile = sourceFile;\n    exportFunctionForFile = undefined;\n    emit(sourceFile);\n}\n```\n\nThe `emit` function handles *comment* emit + *actual JavaScript* emit. The *actual JavaScript* emit is the job of `emitJavaScriptWorker` function.\n\n### `emitJavaScriptWorker`\n\nThe complete function:\n```ts\nfunction emitJavaScriptWorker(node: Node) {\n    // Check if the node can be emitted regardless of the ScriptTarget\n    switch (node.kind) {\n        case SyntaxKind.Identifier:\n            return emitIdentifier(<Identifier>node);\n        case SyntaxKind.Parameter:\n            return emitParameter(<ParameterDeclaration>node);\n        case SyntaxKind.MethodDeclaration:\n        case SyntaxKind.MethodSignature:\n            return emitMethod(<MethodDeclaration>node);\n        case SyntaxKind.GetAccessor:\n        case SyntaxKind.SetAccessor:\n            return emitAccessor(<AccessorDeclaration>node);\n        case SyntaxKind.ThisKeyword:\n            return emitThis(node);\n        case SyntaxKind.SuperKeyword:\n            return emitSuper(node);\n        case SyntaxKind.NullKeyword:\n            return write(\"null\");\n        case SyntaxKind.TrueKeyword:\n            return write(\"true\");\n        case SyntaxKind.FalseKeyword:\n            return write(\"false\");\n        case SyntaxKind.NumericLiteral:\n        case SyntaxKind.StringLiteral:\n        case SyntaxKind.RegularExpressionLiteral:\n        case SyntaxKind.NoSubstitutionTemplateLiteral:\n        case SyntaxKind.TemplateHead:\n        case SyntaxKind.TemplateMiddle:\n        case SyntaxKind.TemplateTail:\n            return emitLiteral(<LiteralExpression>node);\n        case SyntaxKind.TemplateExpression:\n            return emitTemplateExpression(<TemplateExpression>node);\n        case SyntaxKind.TemplateSpan:\n            return emitTemplateSpan(<TemplateSpan>node);\n        case SyntaxKind.JsxElement:\n        case SyntaxKind.JsxSelfClosingElement:\n            return emitJsxElement(<JsxElement|JsxSelfClosingElement>node);\n        case SyntaxKind.JsxText:\n            return emitJsxText(<JsxText>node);\n        case SyntaxKind.JsxExpression:\n            return emitJsxExpression(<JsxExpression>node);\n        case SyntaxKind.QualifiedName:\n            return emitQualifiedName(<QualifiedName>node);\n        case SyntaxKind.ObjectBindingPattern:\n            return emitObjectBindingPattern(<BindingPattern>node);\n        case SyntaxKind.ArrayBindingPattern:\n            return emitArrayBindingPattern(<BindingPattern>node);\n        case SyntaxKind.BindingElement:\n            return emitBindingElement(<BindingElement>node);\n        case SyntaxKind.ArrayLiteralExpression:\n            return emitArrayLiteral(<ArrayLiteralExpression>node);\n        case SyntaxKind.ObjectLiteralExpression:\n            return emitObjectLiteral(<ObjectLiteralExpression>node);\n        case SyntaxKind.PropertyAssignment:\n            return emitPropertyAssignment(<PropertyDeclaration>node);\n        case SyntaxKind.ShorthandPropertyAssignment:\n            return emitShorthandPropertyAssignment(<ShorthandPropertyAssignment>node);\n        case SyntaxKind.ComputedPropertyName:\n            return emitComputedPropertyName(<ComputedPropertyName>node);\n        case SyntaxKind.PropertyAccessExpression:\n            return emitPropertyAccess(<PropertyAccessExpression>node);\n        case SyntaxKind.ElementAccessExpression:\n            return emitIndexedAccess(<ElementAccessExpression>node);\n        case SyntaxKind.CallExpression:\n            return emitCallExpression(<CallExpression>node);\n        case SyntaxKind.NewExpression:\n            return emitNewExpression(<NewExpression>node);\n        case SyntaxKind.TaggedTemplateExpression:\n            return emitTaggedTemplateExpression(<TaggedTemplateExpression>node);\n        case SyntaxKind.TypeAssertionExpression:\n            return emit((<TypeAssertion>node).expression);\n        case SyntaxKind.AsExpression:\n            return emit((<AsExpression>node).expression);\n        case SyntaxKind.ParenthesizedExpression:\n            return emitParenExpression(<ParenthesizedExpression>node);\n        case SyntaxKind.FunctionDeclaration:\n        case SyntaxKind.FunctionExpression:\n        case SyntaxKind.ArrowFunction:\n            return emitFunctionDeclaration(<FunctionLikeDeclaration>node);\n        case SyntaxKind.DeleteExpression:\n            return emitDeleteExpression(<DeleteExpression>node);\n        case SyntaxKind.TypeOfExpression:\n            return emitTypeOfExpression(<TypeOfExpression>node);\n        case SyntaxKind.VoidExpression:\n            return emitVoidExpression(<VoidExpression>node);\n        case SyntaxKind.AwaitExpression:\n            return emitAwaitExpression(<AwaitExpression>node);\n        case SyntaxKind.PrefixUnaryExpression:\n            return emitPrefixUnaryExpression(<PrefixUnaryExpression>node);\n        case SyntaxKind.PostfixUnaryExpression:\n            return emitPostfixUnaryExpression(<PostfixUnaryExpression>node);\n        case SyntaxKind.BinaryExpression:\n            return emitBinaryExpression(<BinaryExpression>node);\n        case SyntaxKind.ConditionalExpression:\n            return emitConditionalExpression(<ConditionalExpression>node);\n        case SyntaxKind.SpreadElementExpression:\n            return emitSpreadElementExpression(<SpreadElementExpression>node);\n        case SyntaxKind.YieldExpression:\n            return emitYieldExpression(<YieldExpression>node);\n        case SyntaxKind.OmittedExpression:\n            return;\n        case SyntaxKind.Block:\n        case SyntaxKind.ModuleBlock:\n            return emitBlock(<Block>node);\n        case SyntaxKind.VariableStatement:\n            return emitVariableStatement(<VariableStatement>node);\n        case SyntaxKind.EmptyStatement:\n            return write(\";\");\n        case SyntaxKind.ExpressionStatement:\n            return emitExpressionStatement(<ExpressionStatement>node);\n        case SyntaxKind.IfStatement:\n            return emitIfStatement(<IfStatement>node);\n        case SyntaxKind.DoStatement:\n            return emitDoStatement(<DoStatement>node);\n        case SyntaxKind.WhileStatement:\n            return emitWhileStatement(<WhileStatement>node);\n        case SyntaxKind.ForStatement:\n            return emitForStatement(<ForStatement>node);\n        case SyntaxKind.ForOfStatement:\n        case SyntaxKind.ForInStatement:\n            return emitForInOrForOfStatement(<ForInStatement>node);\n        case SyntaxKind.ContinueStatement:\n        case SyntaxKind.BreakStatement:\n            return emitBreakOrContinueStatement(<BreakOrContinueStatement>node);\n        case SyntaxKind.ReturnStatement:\n            return emitReturnStatement(<ReturnStatement>node);\n        case SyntaxKind.WithStatement:\n            return emitWithStatement(<WithStatement>node);\n        case SyntaxKind.SwitchStatement:\n            return emitSwitchStatement(<SwitchStatement>node);\n        case SyntaxKind.CaseClause:\n        case SyntaxKind.DefaultClause:\n            return emitCaseOrDefaultClause(<CaseOrDefaultClause>node);\n        case SyntaxKind.LabeledStatement:\n            return emitLabelledStatement(<LabeledStatement>node);\n        case SyntaxKind.ThrowStatement:\n            return emitThrowStatement(<ThrowStatement>node);\n        case SyntaxKind.TryStatement:\n            return emitTryStatement(<TryStatement>node);\n        case SyntaxKind.CatchClause:\n            return emitCatchClause(<CatchClause>node);\n        case SyntaxKind.DebuggerStatement:\n            return emitDebuggerStatement(node);\n        case SyntaxKind.VariableDeclaration:\n            return emitVariableDeclaration(<VariableDeclaration>node);\n        case SyntaxKind.ClassExpression:\n            return emitClassExpression(<ClassExpression>node);\n        case SyntaxKind.ClassDeclaration:\n            return emitClassDeclaration(<ClassDeclaration>node);\n        case SyntaxKind.InterfaceDeclaration:\n            return emitInterfaceDeclaration(<InterfaceDeclaration>node);\n        case SyntaxKind.EnumDeclaration:\n            return emitEnumDeclaration(<EnumDeclaration>node);\n        case SyntaxKind.EnumMember:\n            return emitEnumMember(<EnumMember>node);\n        case SyntaxKind.ModuleDeclaration:\n            return emitModuleDeclaration(<ModuleDeclaration>node);\n        case SyntaxKind.ImportDeclaration:\n            return emitImportDeclaration(<ImportDeclaration>node);\n        case SyntaxKind.ImportEqualsDeclaration:\n            return emitImportEqualsDeclaration(<ImportEqualsDeclaration>node);\n        case SyntaxKind.ExportDeclaration:\n            return emitExportDeclaration(<ExportDeclaration>node);\n        case SyntaxKind.ExportAssignment:\n            return emitExportAssignment(<ExportAssignment>node);\n        case SyntaxKind.SourceFile:\n            return emitSourceFileNode(<SourceFile>node);\n    }\n}\n```\n\nRecursion is done by simply calling other `emitFoo` function from these functions as needed e.g. from `emitFunctionDeclaration` :\n```ts\nfunction emitFunctionDeclaration(node: FunctionLikeDeclaration) {\n    if (nodeIsMissing(node.body)) {\n        return emitOnlyPinnedOrTripleSlashComments(node);\n    }\n\n    if (node.kind !== SyntaxKind.MethodDeclaration && node.kind !== SyntaxKind.MethodSignature) {\n        // Methods will emit the comments as part of emitting method declaration\n        emitLeadingComments(node);\n    }\n\n    // For targeting below es6, emit functions-like declaration including arrow function using function keyword.\n    // When targeting ES6, emit arrow function natively in ES6 by omitting function keyword and using fat arrow instead\n    if (!shouldEmitAsArrowFunction(node)) {\n        if (isES6ExportedDeclaration(node)) {\n            write(\"export \");\n            if (node.flags & NodeFlags.Default) {\n                write(\"default \");\n            }\n        }\n\n        write(\"function\");\n        if (languageVersion >= ScriptTarget.ES6 && node.asteriskToken) {\n            write(\"*\");\n        }\n        write(\" \");\n    }\n\n    if (shouldEmitFunctionName(node)) {\n        emitDeclarationName(node);\n    }\n\n    emitSignatureAndBody(node);\n    if (languageVersion < ScriptTarget.ES6 && node.kind === SyntaxKind.FunctionDeclaration && node.parent === currentSourceFile && node.name) {\n        emitExportMemberAssignments((<FunctionDeclaration>node).name);\n    }\n    if (node.kind !== SyntaxKind.MethodDeclaration && node.kind !== SyntaxKind.MethodSignature) {\n        emitTrailingComments(node);\n    }\n}\n```\n"
  },
  {
    "path": "docs/compiler/emitter-sourcemaps.md",
    "content": "### Emitter SourceMaps\n\nWe said that the bulk of the `emitter.ts` is the local function `emitJavaScript` (we showed the initialization routine of this function before). It basically sets up a bunch of locals and hits off to `emitSourceFile`. The following is a revisiting of the function, this time focusing on `SourceMap` stuff:\n\n```ts\nfunction emitJavaScript(jsFilePath: string, root?: SourceFile) {\n\n    // STUFF ........... removed\n\n    let writeComment = writeCommentRange;\n\n    /** Write emitted output to disk */\n    let writeEmittedFiles = writeJavaScriptFile;\n\n    /** Emit a node */\n    let emit = emitNodeWithoutSourceMap;\n\n    /** Called just before starting emit of a node */\n    let emitStart = function (node: Node) { };\n\n    /** Called once the emit of the node is done */\n    let emitEnd = function (node: Node) { };\n\n    /** Emit the text for the given token that comes after startPos\n      * This by default writes the text provided with the given tokenKind\n      * but if optional emitFn callback is provided the text is emitted using the callback instead of default text\n      * @param tokenKind the kind of the token to search and emit\n      * @param startPos the position in the source to start searching for the token\n      * @param emitFn if given will be invoked to emit the text instead of actual token emit */\n    let emitToken = emitTokenText;\n\n    /** Called to before starting the lexical scopes as in function/class in the emitted code because of node\n      * @param scopeDeclaration node that starts the lexical scope\n      * @param scopeName Optional name of this scope instead of deducing one from the declaration node */\n    let scopeEmitStart = function(scopeDeclaration: Node, scopeName?: string) { };\n\n    /** Called after coming out of the scope */\n    let scopeEmitEnd = function() { };\n\n    /** Sourcemap data that will get encoded */\n    let sourceMapData: SourceMapData;\n\n    if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) {\n        initializeEmitterWithSourceMaps();\n    }\n\n    if (root) {\n        // Do not call emit directly. It does not set the currentSourceFile.\n        emitSourceFile(root);\n    }\n    else {\n        forEach(host.getSourceFiles(), sourceFile => {\n            if (!isExternalModuleOrDeclarationFile(sourceFile)) {\n                emitSourceFile(sourceFile);\n            }\n        });\n    }\n\n    writeLine();\n    writeEmittedFiles(writer.getText(), /*writeByteOrderMark*/ compilerOptions.emitBOM);\n    return;\n\n    /// BUNCH OF LOCAL FUNCTIONS\n```\n\nThe important function call here : `initializeEmitterWithSourceMaps` which is a function local to `emitJavaScript` that overrides some locals that were already defined here. At the bottom of `initializeEmitterWithSourceMaps` you will notice the overriding:\n\n```ts\n    // end of `initializeEmitterWithSourceMaps`\n\n    writeEmittedFiles = writeJavaScriptAndSourceMapFile;\n    emit = emitNodeWithSourceMap;\n    emitStart = recordEmitNodeStartSpan;\n    emitEnd = recordEmitNodeEndSpan;\n    emitToken = writeTextWithSpanRecord;\n    scopeEmitStart = recordScopeNameOfNode;\n    scopeEmitEnd = recordScopeNameEnd;\n    writeComment = writeCommentRangeWithMap;\n```\n\nThis means that the bulk of emitter code can not care about `SourceMap` and just use these local functions the same way with or without SourceMaps.\n"
  },
  {
    "path": "docs/compiler/emitter.md",
    "content": "## Emitter\nThere are two `emitters` provided with the TypeScript compiler:\n\n* `emitter.ts`: this is the emitter you are most likely to be interested in. Its the TS -> JavaScript emitter.\n* `declarationEmitter.ts`: this is the emitter used to create a *declaration file* (a `.d.ts`) for a *TypeScript source file* (a `.ts` file).\n\nWe will look at `emitter.ts` in this section.\n\n### Usage by `program`\nProgram provides an `emit` function. This function primarily delegates to `emitFiles` function in `emitter.ts`. Here is the call stack:\n\n```\nProgram.emit ->\n    `emitWorker` (local in program.ts createProgram) ->\n        `emitFiles` (function in emitter.ts)\n```\nOne thing that the `emitWorker` provides to the emitter (via an argument to `emitFiles`) is an `EmitResolver`. `EmitResolver` is provided by the program's TypeChecker, basically it is a subset of *local* functions from `createChecker`.\n"
  },
  {
    "path": "docs/compiler/make-global.md",
    "content": "## Make TypeScript Global\n\nTypeScript is written using a `namespace ts`. And then the whole compiler is compiled into a single `typescript.js` file. If you want to copy over parts of the source code for exploration a great way to do that is to copy over the portions that you are exploring and then expose them to the global variable `ts`.\n\nA great way to play around with the TypeScript compiler is just to copy the TypeScript compiler source into a folder and then reference it as a `global` variable.\n"
  },
  {
    "path": "docs/compiler/overview.md",
    "content": "# Compiler\nThe TypeScript compiler source is located under the [`src/compiler`](https://github.com/Microsoft/TypeScript/tree/master/src/compiler) folder.\n\nIt is split into the follow key parts:\n* Scanner (`scanner.ts`)\n* Parser (`parser.ts`)\n* Binder (`binder.ts`)\n* Checker (`checker.ts`)\n* Emitter (`emitter.ts`)\n\nEach of these get their own unique files in the source. These parts will be explained later on in this chapter. \n\n## Syntax vs. Semantics\nJust because something is *syntactically* correct doesn't mean it is *semantically* correct. Consider the following piece of TypeScript code which although *syntactically* valid is *semantically* wrong\n\n```ts\nvar foo: number = \"not a number\";\n```\n\n`Semantic` means \"meaning\" in English. This concept is useful to have in your head.\n\n## Processing Overview\nThe following is a quick review of how these key parts of the TypeScript compiler compose:\n\n```code\nSourceCode ~~ scanner ~~> Token Stream\n```\n\n```code\nToken Stream ~~ parser ~~> AST\n```\n\n```code\nAST ~~ binder ~~> Symbols\n```\n`Symbol` is the primary building block of the TypeScript *semantic* system. As shown the symbols are created as a result of binding. Symbols connect declaration nodes in the AST to other declarations contributing to the same entity.\n\nSymbols + AST are what is used by the checker to *semantically* validate the source code\n```code\nAST + Symbols ~~ checker ~~> Type Validation\n```\n\nFinally When a JS output is requested:\n```code\nAST + Checker ~~ emitter ~~> JS\n```\n\nThere are a few additional files in the TypeScript compiler that provide utilities to many of these key portions which we cover next.\n\n## File: Utilities\n`core.ts` : core utilities used by the TypeScript compiler. A few important ones:\n\n* `let objectAllocator: ObjectAllocator` : is a variable defined as a singleton global. It provides the definitions for `getNodeConstructor` (Nodes are covered when we look at `parser` / `AST`), `getSymbolConstructor` (Symbols are covered in `binder`), `getTypeConstructor` (Types are covered in `checker`), `getSignatureConstructor` (Signatures are the index, call and construct signatures).\n\n## File: Key Data Structures\n`types.ts` contains key data structures and interfaces uses throughout the compiler. Here is a sampling of a few key ones:\n* `SyntaxKind`\nThe AST node type is identified by the `SyntaxKind` enum.\n* `TypeChecker`\nThis is the interface provided by the TypeChecker.\n* `CompilerHost`\nThis is used by the `Program` to interact with the `System`.\n* `Node`\nAn AST node.\n\n## File: System\n`system.ts`. All interaction of the TypeScript compiler with the operating system goes through a `System` interface. Both the interface and its implementations (`WScript` and `Node`) are defined in `system.ts`. You can think of it as the *Operating Environment* (OE).\n\nNow that you have an overview of the major files, we can look at the concept of `Program`\n"
  },
  {
    "path": "docs/compiler/parser-functions.md",
    "content": "### Parser Functions\n\nAs mentioned `parseSourceFile` sets up the initial state and passes the work onto `parseSourceFileWorker` function.\n\n#### `parseSourceFileWorker`\n\nStarts by creating a `SourceFile` AST node. Then it goes into parsing source code starting from the `parseStatements` function. Once that returns, it then completes the `SourceFile` node with additional information such as its `nodeCount`, `identifierCount` and such.\n\n#### `parseStatements`\nOne of the most significant `parseFoo` style functions (a concept we cover next). It switches by the current `token` returned from the scanner. E.g. if the current token is a `SemicolonToken` it will call out to `parseEmptyStatement` to create an AST node for an empty statement.\n\n### Node creation\n\nThe parser has a bunch of `parserFoo` functions with bodies that create `Foo` nodes. These are generally called (from other parser functions) at a time where a `Foo` node is expected. A typical sample of this process is the `parseEmptyStatement()` function which is used to parse out empty statements like `;;;;;;`. Here is the function in its entirety\n\n```ts\nfunction parseEmptyStatement(): Statement {\n    let node = <Statement>createNode(SyntaxKind.EmptyStatement);\n    parseExpected(SyntaxKind.SemicolonToken);\n    return finishNode(node);\n}\n```\n\nIt shows three critical functions `createNode`, `parseExpected` and `finishNode`.\n\n#### `createNode`\nThe parser's `createNode` function `function createNode(kind: SyntaxKind, pos?: number): Node` is responsible for creating a Node, setting up its `SyntaxKind` as passed in, and set the initial position if passed in (or use the position from the current scanner state).\n\n#### `parseExpected`\nThe parser's `parseExpected` function `function parseExpected(kind: SyntaxKind, diagnosticMessage?: DiagnosticMessage): boolean` will check that the current token in the parser state matches the desired `SyntaxKind`. If not it will either report the `diagnosticMessage` sent in or create a generic one of the form `foo expected`. It internally uses the `parseErrorAtPosition` function (which uses the scanning positions) to give good error reporting.\n\n### `finishNode`\nThe parser's `finishNode` function `function finishNode<T extends Node>(node: T, end?: number): T` sets up the `end` position for the node and additional useful stuff like the `parserContextFlags` it was parsed under as well as if there were any errors before parsing this node (if there were then we cannot reuse this AST node in incremental parsing).\n"
  },
  {
    "path": "docs/compiler/parser.md",
    "content": "## Parser\nThe sourcecode for the TypeScript parser is located entirely in `parser.ts`. Scanner is *controlled* internally by the `Parser` to convert the source code to an AST. Here is a review of what the desired outcome is.\n\n```\nSourceCode ~~ scanner ~~> Token Stream ~~ parser ~~> AST\n```\n\nThe parser is implemented as a singleton (similar reasons to `scanner`, don't want to recreate it if we can reinit it). It is actually implemented as `namespace Parser` which contains *state* variables for the Parser as well as a singleton `scanner`. As mentioned before it contains a `const scanner`. The parser functions manage this scanner.\n\n### Usage by program\nParser is driven indirectly by Program (indirectly as its actually by `CompilerHost` which we mentioned previously). Basically this is the simplified call stack:\n\n```\nProgram ->\n    CompilerHost.getSourceFile ->\n        (global function parser.ts).createSourceFile ->\n            Parser.parseSourceFile\n```\n\nThe `parseSourceFile` not only primes the state for the Parser but also primes the state for the `scanner` by calling `initializeState`. It then goes on to parse the source file using `parseSourceFileWorker`.\n\n### Sample Usage\nBefore we dig too deep into the parser internals, here is a sample code that uses the TypeScript's parser to get the AST of a source file (using `ts.createSourceFile`), and then print it.\n\n`code/compiler/parser/runParser.ts`\n```ts\nimport * as ts from \"ntypescript\";\n\nfunction printAllChildren(node: ts.Node, depth = 0) {\n    console.log(new Array(depth + 1).join('----'), ts.formatSyntaxKind(node.kind), node.pos, node.end);\n    depth++;\n    node.getChildren().forEach(c=> printAllChildren(c, depth));\n}\n\nvar sourceCode = `\nvar foo = 123;\n`.trim();\n\nvar sourceFile = ts.createSourceFile('foo.ts', sourceCode, ts.ScriptTarget.ES5, true);\nprintAllChildren(sourceFile);\n```\n\nThis will print out the following:\n\n```ts\nSourceFile 0 14\n---- SyntaxList 0 14\n-------- VariableStatement 0 14\n------------ VariableDeclarationList 0 13\n---------------- VarKeyword 0 3\n---------------- SyntaxList 3 13\n-------------------- VariableDeclaration 3 13\n------------------------ Identifier 3 7\n------------------------ FirstAssignment 7 9\n------------------------ FirstLiteralToken 9 13\n------------ SemicolonToken 13 14\n---- EndOfFileToken 14 14\n```\nThis looks like a (very right sided) tree if you tilt your head to the left.\n"
  },
  {
    "path": "docs/compiler/program.md",
    "content": "## Program\n\nDefined in `program.ts`. The compilation context ([a concept we covered previously](../project/compilation-context.md)) is represented within the TypeScript compiler as a `Program`. It consists of `SourceFile`s and compiler options.\n\n\n### Usage of `CompilerHost`\nIts interaction mechanism with the OE:\n\n`Program` *-uses->* `CompilerHost` *-uses->* `System`\n\nThe reason for having a `CompilerHost` as a point of indirection is that it allows its interface to be more finely tuned for `Program` needs and not bother with OE needs (e.g. the `Program` doesn't care about `fileExists` a function provided by `System`).\n\nThere are other users of `System` as well (e.g. tests).\n\n### SourceFile\n\nThe program provides an API to get the Source Files `getSourceFiles(): SourceFile[];`. Each is represented as a root-level node for an AST (called `SourceFile`).\n"
  },
  {
    "path": "docs/compiler/scanner.md",
    "content": "## Scanner\nThe source code for the TypeScript scanner is located entirely in `scanner.ts`. Scanner is *controlled* internally by the `Parser` to convert the source code to an AST. Here is what the desired outcome is.\n\n```\nSourceCode ~~ scanner ~~> Token Stream ~~ parser ~~> AST\n```\n\n### Usage by Parser\nThere is a *singleton* `scanner` created in `parser.ts` to avoid the cost of creating scanners over and over again. This scanner is then *primed* by the parser on demand using the `initializeState` function.\n\nHere is a *simplied* version of the actual code in the parser that you can run demonstrating this concept:\n\n`code/compiler/scanner/runScanner.ts`\n```ts\nimport * as ts from \"ntypescript\";\n\n// TypeScript has a singleton scanner\nconst scanner = ts.createScanner(ts.ScriptTarget.Latest, /*skipTrivia*/ true);\n\n// That is initialized using a function `initializeState` similar to\nfunction initializeState(text: string) {\n    scanner.setText(text);\n    scanner.setOnError((message: ts.DiagnosticMessage, length: number) => {\n        console.error(message);\n    });\n    scanner.setScriptTarget(ts.ScriptTarget.ES5);\n    scanner.setLanguageVariant(ts.LanguageVariant.Standard);\n}\n\n// Sample usage\ninitializeState(`\nvar foo = 123;\n`.trim());\n\n// Start the scanning\nvar token = scanner.scan();\nwhile (token != ts.SyntaxKind.EndOfFileToken) {\n    console.log(ts.formatSyntaxKind(token));\n    token = scanner.scan();\n}\n```\n\nThis will print out the following :\n\n```\nVarKeyword\nIdentifier\nFirstAssignment\nFirstLiteralToken\nSemicolonToken\n```\n\n### Scanner State\nAfter you call `scan` the scanner updates its local state (position in the scan, current token details etc). The scanner provides a bunch of utility functions to get the current scanner state. In the below sample we create a scanner and then use it to identify the tokens as well as their positions in the code.\n\n`code/compiler/scanner/runScannerWithPosition.ts`\n```ts\n// Sample usage\ninitializeState(`\nvar foo = 123;\n`.trim());\n\n// Start the scanning\nvar token = scanner.scan();\nwhile (token != ts.SyntaxKind.EndOfFileToken) {\n    let currentToken = ts.formatSyntaxKind(token);\n    let tokenStart = scanner.getStartPos();\n    token = scanner.scan();\n    let tokenEnd = scanner.getStartPos();\n    console.log(currentToken, tokenStart, tokenEnd);\n}\n```\n\nThis will print out the following:\n```\nVarKeyword 0 3\nIdentifier 3 7\nFirstAssignment 7 9\nFirstLiteralToken 9 13\nSemicolonToken 13 14\n```\n\n### Standalone scanner\nEven though the TypeScript parser has a singleton scanner you can create a standalone scanner using `createScanner` and use its `setText`/`setTextPos` to scan at different points in a file for your amusement.\n"
  },
  {
    "path": "docs/compiler-options.md",
    "content": "// mention Pinned comments\n\n```ts\n/*!\n * License\n */\n```\n"
  },
  {
    "path": "docs/const.md",
    "content": "### const\n\n`const` is a very welcomed addition offered by ES6 / TypeScript. It allows you to be immutable with variables. This is good from a documentation as well as a runtime perspective. To use const just replace `var` with `const`:\n\n```ts\nconst foo = 123;\n```\n\n> The syntax is much better (IMHO) than other languages that force the user to type something like `let constant foo` i.e. a variable + behavior specifier.\n\n`const` is a good practice for both readability and maintainability and avoids using *magic literals* e.g.\n\n```ts\n// Low readability\nif (x > 10) {\n}\n\n// Better!\nconst maxRows = 10;\nif (x > maxRows) {\n}\n```\n\n#### const declarations must be initialized\nThe following is a compiler error:\n\n```ts\nconst foo; // ERROR: const declarations must be initialized\n```\n\n#### Left hand side of assignment cannot be a constant\nConstants are immutable after creation, so if you try to assign them to a new value it is a compiler error:\n\n```ts\nconst foo = 123;\nfoo = 456; // ERROR: Left-hand side of an assignment expression cannot be a constant\n```\n\n#### Block Scoped\nA `const` is block scoped like we saw with [`let`](./let.md):\n\n```ts\nconst foo = 123;\nif (true) {\n    const foo = 456; // Allowed as its a new variable limited to this `if` block\n}\n```\n\n#### Deep immutability\nA `const` works with object literals as well, as far as protecting the variable *reference* is concerned:\n\n```ts\nconst foo = { bar: 123 };\nfoo = { bar: 456 }; // ERROR : Left hand side of an assignment expression cannot be a constant\n```\n\nHowever, it still allows sub properties of objects to be mutated, as shown below:\n\n```ts\nconst foo = { bar: 123 };\nfoo.bar = 456; // Allowed!\nconsole.log(foo); // { bar: 456 }\n```\n\n#### Prefer const\n\nAlways use `const`, unless you plan to either lazily initialization of a variable, or do a reassignment (use `let` for those cases).\n"
  },
  {
    "path": "docs/declaration.md",
    "content": "analogy with c headers\n"
  },
  {
    "path": "docs/destructuring.md",
    "content": "### Destructuring\n\nTypeScript supports the following forms of Destructuring (literally named after de-structuring i.e. breaking up the structure):\n\n1. Object Destructuring\n1. Array Destructuring\n\nIt is easy to think of destructuring as an inverse of *structuring*. The method of *structuring* in JavaScript is the object literal:\n\n```ts\nvar foo = {\n    bar: {\n        bas: 123\n    }\n};\n```\nWithout the awesome *structuring* support built into JavaScript, creating new objects on the fly would indeed be very cumbersome. Destructuring brings the same level of convenience to getting data out of a structure.\n\n#### Object Destructuring\nDestructuring is useful because it allows you to do in a single line, what would otherwise require multiple lines. Consider the following case:\n\n```ts\nvar rect = { x: 0, y: 10, width: 15, height: 20 };\n\n// Destructuring assignment\nvar {x, y, width, height} = rect;\nconsole.log(x, y, width, height); // 0,10,15,20\n\nrect.x = 10;\n({x, y, width, height} = rect); // assign to existing variables using outer parentheses\nconsole.log(x, y, width, height); // 10,10,15,20\n```\nHere in the absence of destructuring you would have to pick off `x,y,width,height` one by one from `rect`.\n\nTo assign an extracted variable to a new variable name you can do the following:\n\n```ts\n// structure\nconst obj = {\"some property\": \"some value\"};\n\n// destructure\nconst {\"some property\": someProperty} = obj;\nconsole.log(someProperty === \"some value\"); // true\n```\n\nAdditionally you can get *deep* data out of a structure using destructuring. This is shown in the following example:\n\n```ts\nvar foo = { bar: { bas: 123 } };\nvar {bar: {bas}} = foo; // Effectively `var bas = foo.bar.bas;`\n```\n\n#### Object Destructuring with rest\nYou can pick up any number of elements from an object and get *an object* of the remaining elements using object destructuring with rest.\n\n```ts\nvar {w, x, ...remaining} = {w: 1, x: 2, y: 3, z: 4};\nconsole.log(w, x, remaining); // 1, 2, {y:3,z:4}\n```\nA common use case is also to ignore certain properties. For example:\n```ts\n// Example function\nfunction goto(point2D: {x: number, y: number}) {\n  // Imagine some code that might break\n  // if you pass in an object\n  // with more items than desired\n}\n// Some point you get from somewhere\nconst point3D = {x: 1, y: 2, z: 3};\n/** A nifty use of rest to remove extra properties */\nconst { z, ...point2D } = point3D;\ngoto(point2D);\n```\n\n#### Array Destructuring\nA common programming question: \"How to swap two variables without using a third one?\". The TypeScript solution:\n\n```ts\nvar x = 1, y = 2;\n[x, y] = [y, x];\nconsole.log(x, y); // 2,1\n```\nNote that array destructuring is effectively the compiler doing the `[0], [1], ...` and so on for you. There is no guarantee that these values will exist.\n\n#### Array Destructuring with rest\nYou can pick up any number of elements from an array and get *an array* of the remaining elements using array destructuring with rest.\n\n```ts\nvar [x, y, ...remaining] = [1, 2, 3, 4];\nconsole.log(x, y, remaining); // 1, 2, [3,4]\n```\n\n#### Array Destructuring with ignores\nYou can ignore any index by simply leaving its location empty i.e. `, ,` in the left hand side of the assignment. For example:\n```ts\nvar [x, , ...remaining] = [1, 2, 3, 4];\nconsole.log(x, remaining); // 1, [3,4]\n```\n\n#### JS Generation\nThe JavaScript generation for non ES6 targets simply involves creating temporary variables, just like you would have to do yourself without native language support for destructuring e.g.\n\n```ts\nvar x = 1, y = 2;\n[x, y] = [y, x];\nconsole.log(x, y); // 2,1\n\n// becomes //\n\nvar x = 1, y = 2;\n_a = [y,x], x = _a[0], y = _a[1];\nconsole.log(x, y);\nvar _a;\n```\n\n#### Summary\nDestructuring can make your code more readable and maintainable by reducing the line count and making the intent clear. Array destructuring can allow you to use arrays as though they were tuples.\n"
  },
  {
    "path": "docs/enums.md",
    "content": "* [Enums](#enums)\n* [Number Enums and numbers](#number-enums-and-numbers)\n* [Number Enums and strings](#number-enums-and-strings)\n* [Changing the number associated with a number enum](#changing-the-number-associated-with-a-number-enum)\n* [Enums are open ended](#enums-are-open-ended)\n* [Number Enums as flags](#number-enums-as-flags)\n* [String Enums](#string-enums)\n* [Const enums](#const-enums)\n* [Enum with static functions](#enum-with-static-functions)\n\n### Enums\nAn enum is a way to organize a collection of related values. Many other programming languages (C/C#/Java) have an `enum` data type but JavaScript does not. However, TypeScript does. Here is an example definition of a TypeScript enum:\n\n```ts\nenum CardSuit {\n\tClubs,\n\tDiamonds,\n\tHearts,\n\tSpades\n}\n\n// Sample usage\nvar card = CardSuit.Clubs;\n\n// Safety\ncard = \"not a member of card suit\"; // Error : string is not assignable to type `CardSuit`\n```\n\nThese enums values are `number`s so I'll call them Number Enums from hence forth.\n\n#### Number Enums and Numbers\nTypeScript enums are number based. This means that numbers can be assigned to an instance of the enum, and so can anything else that is compatible with `number`.\n\n```ts\nenum Color {\n    Red,\n    Green,\n    Blue\n}\nvar col = Color.Red;\ncol = 0; // Effectively same as Color.Red\n```\n\n#### Number Enums and Strings\nBefore we look further into enums let's look at the JavaScript that it generates, here is a sample TypeScript:\n\n```ts\nenum Tristate {\n    False,\n    True,\n    Unknown\n}\n```\ngenerates the following JavaScript:\n\n```js\nvar Tristate;\n(function (Tristate) {\n    Tristate[Tristate[\"False\"] = 0] = \"False\";\n    Tristate[Tristate[\"True\"] = 1] = \"True\";\n    Tristate[Tristate[\"Unknown\"] = 2] = \"Unknown\";\n})(Tristate || (Tristate = {}));\n```\n\nlet's focus on the line `Tristate[Tristate[\"False\"] = 0] = \"False\";`. Within it `Tristate[\"False\"] = 0` should be self explanatory, i.e. sets `\"False\"` member of `Tristate` variable to be `0`. Note that in JavaScript the assignment operator returns the assigned value (in this case `0`). Therefore the next thing executed by the JavaScript runtime is `Tristate[0] = \"False\"`. This means that you can use the `Tristate` variable to convert a string version of the enum to a number or a number version of the enum to a string. This is demonstrated below:\n\n```ts\nenum Tristate {\n    False,\n    True,\n    Unknown\n}\nconsole.log(Tristate[0]); // \"False\"\nconsole.log(Tristate[\"False\"]); // 0\nconsole.log(Tristate[Tristate.False]); // \"False\" because `Tristate.False == 0`\n```\n\n#### Changing the number associated with a Number Enum\nBy default enums are `0` based and then each subsequent value increments by 1 automatically. As an example consider the following:\n\n```ts\nenum Color {\n    Red,     // 0\n    Green,   // 1\n    Blue     // 2\n}\n```\n\nHowever, you can change the number associated with any enum member by assigning to it specifically. This is demonstrated below where we start at 3 and start incrementing from there:\n\n```ts\nenum Color {\n    DarkRed = 3,  // 3\n    DarkGreen,    // 4\n    DarkBlue      // 5\n}\n```\n\n> TIP: I quite commonly initialize the first enum with ` = 1` as it allows me to do a safe truthy check on an enum value.\n\n#### Number Enums as flags\nOne excellent use of enums is the ability to use enums as `Flags`. Flags allow you to check if a certain condition from a set of conditions is true. Consider the following example where we have a set of properties about animals:\n\n```ts\nenum AnimalFlags {\n    None           = 0,\n    HasClaws       = 1 << 0,\n    CanFly         = 1 << 1,\n    EatsFish       = 1 << 2,\n    Endangered     = 1 << 3\n}\n```\n\nHere we are using the left shift operator to move `1` around a certain level of bits to come up with bitwise disjoint numbers `0001`, `0010`, `0100` and `1000` (these are decimals `1`,`2`,`4`,`8` if you are curious). The bitwise operators `|` (or) / `&` (and) / `~` (not) are your best friends when working with flags and are demonstrated below:\n\n```ts\nenum AnimalFlags {\n    None           = 0,\n    HasClaws       = 1 << 0,\n    CanFly         = 1 << 1,\n}\ntype Animal = {\n    flags: AnimalFlags\n}\n\nfunction printAnimalAbilities(animal: Animal) {\n    var animalFlags = animal.flags;\n    if (animalFlags & AnimalFlags.HasClaws) {\n        console.log('animal has claws');\n    }\n    if (animalFlags & AnimalFlags.CanFly) {\n        console.log('animal can fly');\n    }\n    if (animalFlags == AnimalFlags.None) {\n        console.log('nothing');\n    }\n}\n\nlet animal: Animal = { flags: AnimalFlags.None };\nprintAnimalAbilities(animal); // nothing\nanimal.flags |= AnimalFlags.HasClaws;\nprintAnimalAbilities(animal); // animal has claws\nanimal.flags &= ~AnimalFlags.HasClaws;\nprintAnimalAbilities(animal); // nothing\nanimal.flags |= AnimalFlags.HasClaws | AnimalFlags.CanFly;\nprintAnimalAbilities(animal); // animal has claws, animal can fly\n```\n\nHere:\n* we used `|=` to add flags\n* a combination of `&=` and `~` to clear a flag\n* `|` to combine flags\n\n> Note: you can combine flags to create convenient shortcuts within the enum definition e.g. `EndangeredFlyingClawedFishEating` below:\n\n```ts\nenum AnimalFlags {\n\tNone           = 0,\n    HasClaws       = 1 << 0,\n    CanFly         = 1 << 1,\n    EatsFish       = 1 << 2,\n    Endangered     = 1 << 3,\n\n\tEndangeredFlyingClawedFishEating = HasClaws | CanFly | EatsFish | Endangered,\n}\n```\n\n#### String Enums\nWe've only looked at enums where the member values are `number`s. You are actually allowed to have enum members with string values as well. e.g. \n\n```ts\nexport enum EvidenceTypeEnum {\n  UNKNOWN = '',\n  PASSPORT_VISA = 'passport_visa',\n  PASSPORT = 'passport',\n  SIGHTED_STUDENT_CARD = 'sighted_tertiary_edu_id',\n  SIGHTED_KEYPASS_CARD = 'sighted_keypass_card',\n  SIGHTED_PROOF_OF_AGE_CARD = 'sighted_proof_of_age_card',\n}\n```\n\nThese can be easier to deal with and debug as they provide meaningful / debuggable string values. \n\nYou can use these values to do simple string comparisons. e.g. \n\n```ts\n// Where `someStringFromBackend` will be '' | 'passport_visa' | 'passport' ... etc.\nconst value = someStringFromBackend as EvidenceTypeEnum; \n\n// Sample use in code\nif (value === EvidenceTypeEnum.PASSPORT){\n    console.log('You provided a passport');\n    console.log(value); // `passport`\n}\n```\n\n#### Const Enums\n\nIf you have an enum definition like the following:\n\n```ts\nenum Tristate {\n    False,\n    True,\n    Unknown\n}\n\nvar lie = Tristate.False;\n```\n\nThe line `var lie = Tristate.False` is compiled to the JavaScript `var lie = Tristate.False` (yes, output is same as input). This means that at execution the runtime will need to lookup `Tristate` and then `Tristate.False`. To get a performance boost here you can mark the `enum` as a `const enum`. This is demonstrated below:\n\n```ts\nconst enum Tristate {\n    False,\n    True,\n    Unknown\n}\n\nvar lie = Tristate.False;\n```\n\ngenerates the JavaScript:\n\n```js\nvar lie = 0;\n```\n\ni.e. the compiler:\n\n1. *Inlines* any usages of the enum (`0` instead of `Tristate.False`).\n1. Does not generate any JavaScript for the enum definition (there is no `Tristate` variable at runtime) as its usages are inlined.\n\n##### Const enum preserveConstEnums\nInlining has obvious performance benefits. The fact that there is no `Tristate` variable at runtime is simply the compiler helping you out by not generating JavaScript that is not actually used at runtime. However, you might want the compiler to still generate the JavaScript version of the enum definition for stuff like *number to string* or *string to number* lookups as we saw. In this case you can use the compiler flag `--preserveConstEnums` and it will still generate the `var Tristate` definition so that you can use `Tristate[\"False\"]` or `Tristate[0]` manually at runtime if you want. This does not impact *inlining* in any way.\n\n### Enum with static functions\nYou can use the declaration `enum` + `namespace` merging to add static methods to an enum. The following demonstrates an example where we add a static member `isBusinessDay` to an enum `Weekday`:\n\n```ts\nenum Weekday {\n\tMonday,\n\tTuesday,\n\tWednesday,\n\tThursday,\n\tFriday,\n\tSaturday,\n\tSunday\n}\nnamespace Weekday {\n\texport function isBusinessDay(day: Weekday) {\n\t\tswitch (day) {\n\t\t\tcase Weekday.Saturday:\n\t\t\tcase Weekday.Sunday:\n\t\t\t\treturn false;\n\t\t\tdefault:\n\t\t\t\treturn true;\n\t\t}\n\t}\n}\n\nconst mon = Weekday.Monday;\nconst sun = Weekday.Sunday;\nconsole.log(Weekday.isBusinessDay(mon)); // true\nconsole.log(Weekday.isBusinessDay(sun)); // false\n```\n\n#### Enums are open ended\n\n> NOTE: open ended enums are only relevant if you are not using modules. You should be using modules. Hence this section is last.\n\nHere is the generated JavaScript for an enum shown again:\n\n```js\nvar Tristate;\n(function (Tristate) {\n    Tristate[Tristate[\"False\"] = 0] = \"False\";\n    Tristate[Tristate[\"True\"] = 1] = \"True\";\n    Tristate[Tristate[\"Unknown\"] = 2] = \"Unknown\";\n})(Tristate || (Tristate = {}));\n```\n\nWe already explained the `Tristate[Tristate[\"False\"] = 0] = \"False\";` portion. Now notice the surrounding code `(function (Tristate) { /*code here */ })(Tristate || (Tristate = {}));` specifically the `(Tristate || (Tristate = {}));` portion. This basically captures a local variable `TriState` that will either point to an already defined `Tristate` value or initialize it with a new empty `{}` object.\n\nThis means that you can split (and extend) an enum definition across multiple files. For example below we have split the definition for `Color` into two blocks\n\n```ts\nenum Color {\n    Red,\n    Green,\n    Blue\n}\n\nenum Color {\n    DarkRed = 3,\n    DarkGreen,\n    DarkBlue\n}\n```\n\nNote that you *should* reinitialize the first member (here `DarkRed = 3`) in a continuation of an enum to get the generated code not clobber values from a previous definition (i.e. the `0`, `1`, ... so on values). TypeScript will warn you if you don't anyways (error message `In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element.`).\n"
  },
  {
    "path": "docs/errors/common-errors.md",
    "content": "# Common Errors\nIn this section we explain a number of common error codes that users experience in the real world.\n\n## TS2304\nSamples:\n> `Cannot find name ga`\n> `Cannot find name $`\n> `Cannot find module jquery`\n\nYou are probably using a third party library (e.g. google analytics) and don't have it `declare`d. TypeScript tries to save you from *spelling mistakes* and *using variables without declaring them* so you need to be explicit on anything that is *available at runtime* because of you including some external library ([more on how to fix it][ambient]).\n\n## TS2307\nSamples:\n> `Cannot find module 'underscore'`\n\nYou are probably using a third party library (e.g. underscore) as a *module* ([more on modules][modules]) and don't have the ambient declaration file for it ([more on ambient declarations][ambient]).\n\n## TS1148\nSample:\n> Cannot compile modules unless the '--module' flag is provided\n\nCheckout the [section on modules][modules].\n\n## Catch clause variable cannot have a type annotation\nSample:\n```js\ntry { something(); }\ncatch (e: Error) { // Catch clause variable cannot have a type annotation\n}\n```\nTypeScript is protecting you from JavaScript code in the wild being wrong. Use a type guard instead:\n```js\ntry { something(); }\ncatch (e) {\n  if (e instanceof Error){\n    // Here you go.\n  }\n}\n```\n\n## Interface `ElementClass` cannot simultaneously extend types `Component` and `Component`\nThis happens when you have two `react.d.ts` (`@types/react/index.d.ts`) in the compilation context.\n\n**Fix**:\n* Delete `node_modules` and any `package-lock` (or yarn lock) and `npm install` again.\n* If it doesn't work, find the invalid module (all modules used by your project should have `react.d.ts` as a `peerDependency` and not a hard `dependency`) and report it on their project.\n\n\n[ambient]: ../types/ambient/d.ts.md\n[modules]: ../project/modules.md\n"
  },
  {
    "path": "docs/errors/interpreting-errors.md",
    "content": "# Interpreting Errors \nSince TypeScript is a heavily focused *Developer Help* oriented programming language, its errors messages try to be super helpful when something goes wrong. This can lead to a slight information overload for unsuspecting users of compilers that aren't so helpful. \n\nLets look at an example in an IDE to break apart the process of reading an error message. \n\n```ts\ntype SomethingComplex = {\n  foo: number,\n  bar: string\n}\nfunction takeSomethingComplex(arg: SomethingComplex) {\n}\nfunction getBar(): string {\n  return 'some bar';\n}\n\n//////////////////////////////////\n// Example error production\n//////////////////////////////////\nconst fail = {\n  foo: 123,\n  bar: getBar\n};\n\ntakeSomethingComplex(fail); // TS ERROR HAPPENS HERE \n```\n\nThis example demonstrates a common programmer error where they *fail* to call a function (`bar: getBar` should be `bar: getBar()`). Fortunately this mistake is caught by TypeScript as soon as it doesn't meet the type requirements. \n\n## Error Categories\nThere are two categories of TypeScript Error messages (succinct and detailed). \n\n### Succinct\nThe objective of the succinct error message is to provide an example *conventional compiler* description of the error number and message. For this example the succinct message looks like: \n\n```\nTS2345: Argument of type '{ foo: number; bar: () => string; }' is not assignable to parameter of type 'SomethingComplex'.\n```\nIt is fairly self explanatory. However, it doesn't provide a deeper breakdown of *why* the error is happening. That is what the *detailed* error message is for.\n\n### Detailed\nFor this example the detailed version looks like: \n\n```\n[ts]\nArgument of type '{ foo: number; bar: () => string; }' is not assignable to parameter of type 'SomethingComplex'.\n  Types of property 'bar' are incompatible.\n    Type '() => string' is not assignable to type 'string'.\n```\nThe objective of the detailed error message is to *guide* the user to the reason why some error (type incompatibility in this case) is happening. The first line is same as the succinct, followed by a chain. You should read this chain as a series of responses to the developer question `WHY?` between lines i.e \n\n```\nERROR: Argument of type '{ foo: number; bar: () => string; }' is not assignable to parameter of type 'SomethingComplex'.\n\nWHY? \nCAUSE ERROR: Types of property 'bar' are incompatible.\n\nWHY? \nCAUSE ERROR: Type '() => string' is not assignable to type 'string'.\n```\n\nSo the root cause is,\n* for property `bar`\n* there is a function `() => string` while it was expected as a `string`. \n\nThis should help the developer fix the bug for the `bar` property (they forgot to invoke `()` the function).\n\n## How it shows up in an IDE Tooltip \n\nThe IDE normally shows the `detailed` followed by the `succinct` version in a tooltip as shown below: \n\n![IDE error message example](https://raw.githubusercontent.com/basarat/typescript-book/master/images/errors/interpreting-errors/ide.png)\n\n* You normally just read the `detailed` version forming the `WHY?` chain in your head. \n* You use the succinct version if you want to search for similar errors (using the `TSXXXX` error code or portions of the error message)\n"
  },
  {
    "path": "docs/errors/main.md",
    "content": "# Errors \nIn this section we discuss how to read and understand TypeScript errors. We follow this with common errors and their solutions.\n"
  },
  {
    "path": "docs/for...of.md",
    "content": "### for...of\nA common error experienced by beginning JavaScript developers is that `for...in` for an array does not iterate over the array items. Instead it iterates over the *keys* of the object passed in. This is demonstrated in the below example. Here you would expect `9,2,5` but you get the indexes `0,1,2`:\n\n```ts\nvar someArray = [9, 2, 5];\nfor (var item in someArray) {\n    console.log(item); // 0,1,2\n}\n```\n\nThis is one of the reasons why `for...of` exists in TypeScript (and ES6). The following iterates over the array correctly logging out the members as expected:\n\n```ts\nvar someArray = [9, 2, 5];\nfor (var item of someArray) {\n    console.log(item); // 9,2,5\n}\n```\n\nSimilarly TypeScript has no trouble going through a string character by character using `for...of`:\n\n```ts\nvar hello = \"is it me you're looking for?\";\nfor (var char of hello) {\n    console.log(char); // is it me you're looking for?\n}\n```\n\n#### JS Generation\nFor pre ES6 targets TypeScript will generate the standard `for (var i = 0; i < list.length; i++)` kind of loop. For example here's what gets generated for our previous example:\n```ts\nvar someArray = [9, 2, 5];\nfor (var item of someArray) {\n    console.log(item);\n}\n\n// becomes //\n\nfor (var _i = 0; _i < someArray.length; _i++) {\n    var item = someArray[_i];\n    console.log(item);\n}\n```\nYou can see that using `for...of` makes *intent* clearer and also decreases the amount of code you have to write (and variable names you need to come up with).\n\n#### Limitations\nIf you are not targeting ES6 or above, the generated code assumes the property `length` exists on the object and that the object can be indexed via numbers e.g. `obj[2]`. So it is only supported on `string` and `array` for these legacy JS engines.\n\nIf TypeScript can see that you are not using an array or a string it will give you a clear error *\"is not an array type or a string type\"*;\n```ts\nlet articleParagraphs = document.querySelectorAll(\"article > p\");\n// Error: Nodelist is not an array type or a string type\nfor (let paragraph of articleParagraphs) {\n    paragraph.classList.add(\"read\");\n}\n```\n\nUse `for...of` only for stuff that *you know* to be an array or a string. Note that this limitation might be removed in a future version of TypeScript.\n\n#### Summary\nYou would be surprised at how many times you will be iterating over the elements of an array. The next time you find yourself doing that, give `for...of` a go. You might just make the next person who reviews your code happy.\n"
  },
  {
    "path": "docs/future-javascript.md",
    "content": "# Future JavaScript: Now\nOne of the main selling points of TypeScript is that it allows you to use a bunch of features from ES6 and beyond in current (ES3 and ES5 level) JavaScript engines (like current browsers and Node.js). Here we deep dive into why these features are useful followed by how these features are implemented in TypeScript.\n\nNote: Not all of these features are slated for immediate addition to JavaScript but provide great utility to your code organization and maintenance. Also note that you are free to ignore any of the constructs that don't make sense for your project, although you will end up using most of them eventually ;)\n"
  },
  {
    "path": "docs/generators.md",
    "content": "## Generators\n\n`function *` is the syntax used to create a *generator function*. Calling a generator function returns a *generator object*. The generator object just follows the [iterator][iterator] interface (i.e. the `next`, `return` and `throw` functions). \n\nThere are two key motivations behind generator functions: \n\n### Lazy Iterators\n\nGenerator functions can be used to create lazy iterators e.g. the following function returns an **infinite** list of integers on demand:\n\n```ts\nfunction* infiniteSequence() {\n    var i = 0;\n    while(true) {\n        yield i++;\n    }\n}\n\nvar iterator = infiniteSequence();\nwhile (true) {\n    console.log(iterator.next()); // { value: xxxx, done: false } forever and ever\n}\n```\n\nOf course if the iterator does end, you get the result of `{ done: true }` as demonstrated below:\n\n```ts\nfunction* idMaker(){\n  let index = 0;\n  while(index < 3)\n    yield index++;\n}\n\nlet gen = idMaker();\n\nconsole.log(gen.next()); // { value: 0, done: false }\nconsole.log(gen.next()); // { value: 1, done: false }\nconsole.log(gen.next()); // { value: 2, done: false }\nconsole.log(gen.next()); // { done: true }\n```\n\n### Externally Controlled Execution\nThis is the part of generators that is truly exciting. It essentially allows a function to pause its execution and pass control (fate) of the remainder of the function execution to the caller.\n\nA generator function does not execute when you call it. It just creates a generator object. Consider the following example along with a sample execution:\n\n```ts\nfunction* generator(){\n    console.log('Execution started');\n    yield 0;\n    console.log('Execution resumed');\n    yield 1;\n    console.log('Execution resumed');\n}\n\nvar iterator = generator();\nconsole.log('Starting iteration'); // This will execute before anything in the generator function body executes\nconsole.log(iterator.next()); // { value: 0, done: false }\nconsole.log(iterator.next()); // { value: 1, done: false }\nconsole.log(iterator.next()); // { value: undefined, done: true }\n```\n\nIf you run this you get the following output:\n\n```\n$ node outside.js\nStarting iteration\nExecution started\n{ value: 0, done: false }\nExecution resumed\n{ value: 1, done: false }\nExecution resumed\n{ value: undefined, done: true }\n```\n\n* The function only starts execution once `next` is called on the generator object.\n* The function *pauses* as soon as a `yield` statement is encountered.\n* The function *resumes* when `next` is called.\n\n> So essentially the execution of the generator function is controllable by the generator object.\n\nOur communication using the generator has been mostly one way with the generator returning values for the iterator. One extremely powerful feature of generators in JavaScript is that they allow two way communications (with caveats).\n\n* you can control the resulting value of the `yield` expression using `iterator.next(valueToInject)`\n* you can throw an exception at the point of the `yield` expression using `iterator.throw(error)`\n\nThe following example demonstrates `iterator.next(valueToInject)`:\n\n```ts\nfunction* generator() {\n    const bar = yield 'foo'; // bar may be *any* type\n    console.log(bar); // bar!\n}\n\nconst iterator = generator();\n// Start execution till we get first yield value\nconst foo = iterator.next();\nconsole.log(foo.value); // foo\n// Resume execution injecting bar\nconst nextThing = iterator.next('bar');\n```\n\nSince `yield` returns the parameter passed to the iterator's `next` function, and all iterators' `next` functions accept a parameter of any type, TypeScript will always assign the `any` type to the result of the `yield` operator (`bar` above).\n\n> You are on your own to coerce the result to the type you expect, and ensure that only values of that type are passed to next (such as by scaffolding an additional type-enforcement layer that calls `next` for you.) If strong typing is important to you, you may want to avoid two-way communication altogether, as well as packages that rely heavily on it (e.g., redux-saga).\n\nThe following example demonstrates `iterator.throw(error)`:\n\n```ts\nfunction* generator() {\n    try {\n        yield 'foo';\n    }\n    catch(err) {\n        console.log(err.message); // bar!\n    }\n}\n\nvar iterator = generator();\n// Start execution till we get first yield value\nvar foo = iterator.next();\nconsole.log(foo.value); // foo\n// Resume execution throwing an exception 'bar'\nvar nextThing = iterator.throw(new Error('bar'));\n```\n\nSo here is the summary:\n* `yield` allows a generator function to pause its communication and pass control to an external system\n* the external system can push a value into the generator function body\n* the external system can throw an exception into the generator function body\n\nHow is this useful? Jump to the next section [**async/await**][async-await] and find out.\n\n[iterator]:./iterators.md\n[async-await]:./async-await.md\n"
  },
  {
    "path": "docs/getting-started.md",
    "content": "* [Getting Started with TypeScript](#getting-started-with-typescript)\n* [TypeScript Version](#typescript-version)\n\n# Getting Started With TypeScript\n\nTypeScript compiles into JavaScript. JavaScript is what you are actually going to execute (either in the browser or on the server). So you are going to need the following:\n\n* TypeScript compiler (OSS available [in source](https://github.com/Microsoft/TypeScript/) and on [NPM](https://www.npmjs.com/package/typescript))\n* A TypeScript editor (you can use notepad if you want but I use [vscode 🌹](https://code.visualstudio.com/) with an [extension I wrote](https://marketplace.visualstudio.com/items?itemName=basarat.god). Also [lots of other IDES support it as well]( https://github.com/Microsoft/TypeScript/wiki/TypeScript-Editor-Support))\n\n\n## TypeScript Version\n\nInstead of using the *stable* TypeScript compiler we will be presenting a lot of new stuff in this book that may not be associated with a version number yet. I generally recommend people to use the nightly version because **the compiler test suite only catches more bugs over time**.\n\nYou can install it on the command line as\n\n```\nnpm install -g typescript@next\n```\n\nAnd now the command line `tsc` will be the latest and greatest. Various IDEs support it too, e.g.\n\n* You can ask vscode to use this version by creating `.vscode/settings.json` with the following contents:\n\n```json\n{\n  \"typescript.tsdk\": \"./node_modules/typescript/lib\"\n}\n```\n\n## Getting the Source Code\nThe source for this book is available in the books github repository https://github.com/basarat/typescript-book/tree/master/code most of the code samples can be copied into vscode and you can play with them as is. For code samples that need additional setup (e.g. npm modules), we will link you to the code sample before presenting the code. e.g.\n\n`this/will/be/the/link/to/the/code.ts`\n```ts\n// This will be the code under discussion\n```\n\nWith a dev setup out of the way let's jump into TypeScript syntax.\n"
  },
  {
    "path": "docs/iterators.md",
    "content": "### Iterators\n\nIterator itself is not a TypeScript or ES6 feature, Iterator is a\nBehavioral Design Pattern common for Object oriented programming languages.\nIt is, generally, an object which implements the following interface:\n\n```ts\ninterface Iterator<T> {\n    next(value?: any): IteratorResult<T>;\n    return?(value?: any): IteratorResult<T>;\n    throw?(e?: any): IteratorResult<T>;\n}\n```\n([More on that `<T>` notation later][generics])  \nThis interface allows to retrieve a value from some collection or sequence\nwhich belongs to the object.\n\nThe `IteratorResult` is simply a `value`+`done` pair: \n```ts\ninterface IteratorResult<T> {\n    done: boolean;\n    value: T;\n}\n```\n\nImagine that there's an object of some frame, which includes the list of\ncomponents of which this frame consists. With Iterator interface it is possible\nto retrieve components from this frame object like below:\n\n```ts\nclass Component {\n  constructor (public name: string) {}\n}\n\nclass Frame implements Iterator<Component> {\n\n  private pointer = 0;\n\n  constructor(public name: string, public components: Component[]) {}\n\n  public next(): IteratorResult<Component> {\n    if (this.pointer < this.components.length) {\n      return {\n        done: false,\n        value: this.components[this.pointer++]\n      }\n    } else {\n      return {\n        done: true,\n        value: null\n      }\n    }\n  }\n\n}\n\nlet frame = new Frame(\"Door\", [new Component(\"top\"), new Component(\"bottom\"), new Component(\"left\"), new Component(\"right\")]);\nlet iteratorResult1 = frame.next(); //{ done: false, value: Component { name: 'top' } }\nlet iteratorResult2 = frame.next(); //{ done: false, value: Component { name: 'bottom' } }\nlet iteratorResult3 = frame.next(); //{ done: false, value: Component { name: 'left' } }\nlet iteratorResult4 = frame.next(); //{ done: false, value: Component { name: 'right' } }\nlet iteratorResult5 = frame.next(); //{ done: true, value: null }\n\n//It is possible to access the value of iterator result via the value property:\nlet component = iteratorResult1.value; //Component { name: 'top' }\n```\nAgain. Iterator itself is not a TypeScript feature, this code could work without\nimplementing Iterator and IteratorResult interfaces explicitly.\nHowever, it is very helpful to use these common\nES6 [interfaces](./types/interfaces.md) for code consistency.\n\nOk, Nice, but could be more helpful. ES6 defines the *iterable protocol*\nwhich includes the [Symbol.iterator] `symbol` if the Iterable interface is implemented:\n```ts\n//...\nclass Frame implements Iterable<Component> {\n\n  constructor(public name: string, public components: Component[]) {}\n\n  [Symbol.iterator]() {\n    let pointer = 0;\n    let components = this.components;\n\n    return {\n      next(): IteratorResult<Component> {\n        if (pointer < components.length) {\n          return {\n            done: false,\n            value: components[pointer++]\n          }\n        } else {\n          return {\n            done: true,\n            value: null\n          }\n        }\n      }\n    }\n  }\n}\n\nlet frame = new Frame(\"Door\", [new Component(\"top\"), new Component(\"bottom\"), new Component(\"left\"), new Component(\"right\")]);\nfor (let cmp of frame) {\n  console.log(cmp);\n}\n```\n\nUnfortunately `frame.next()` won't work with this pattern and it also looks\na bit clunky. IterableIterator interface to the rescue!\n```ts\n//...\nclass Frame implements IterableIterator<Component> {\n\n  private pointer = 0;\n\n  constructor(public name: string, public components: Component[]) {}\n\n  public next(): IteratorResult<Component> {\n    if (this.pointer < this.components.length) {\n      return {\n        done: false,\n        value: this.components[this.pointer++]\n      }\n    } else {\n      return {\n        done: true,\n        value: null\n      }\n    }\n  }\n\n  [Symbol.iterator](): IterableIterator<Component> {\n    return this;\n  }\n\n}\n//...\n```\nBoth `frame.next()` and `for` cycle now work fine with IterableIterator interface.\n\nIterator does not have to iterate a finite value.\nThe typical example is a Fibonacci sequence:\n```ts\nclass Fib implements IterableIterator<number> {\n\n  protected fn1 = 0;\n  protected fn2 = 1;\n\n  constructor(protected maxValue?: number) {}\n\n  public next(): IteratorResult<number> {\n    var current = this.fn1;\n    this.fn1 = this.fn2;\n    this.fn2 = current + this.fn1;\n    if (this.maxValue != null && current >= this.maxValue) {\n      return {\n        done: true,\n        value: null\n      } \n    } \n    return {\n      done: false,\n      value: current\n    }\n  }\n\n  [Symbol.iterator](): IterableIterator<number> {\n    return this;\n  }\n\n}\n\nlet fib = new Fib();\n\nfib.next() //{ done: false, value: 0 }\nfib.next() //{ done: false, value: 1 }\nfib.next() //{ done: false, value: 1 }\nfib.next() //{ done: false, value: 2 }\nfib.next() //{ done: false, value: 3 }\nfib.next() //{ done: false, value: 5 }\n\nlet fibMax50 = new Fib(50);\nconsole.log(Array.from(fibMax50)); // [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ]\n\nlet fibMax21 = new Fib(21);\nfor(let num of fibMax21) {\n  console.log(num); //Prints fibonacci sequence 0 to 21\n}\n```\n\n#### Building code with iterators for ES5 target\nCode examples above require ES6 target. However, it could work\nwith ES5 target as well if target JS engine supports `Symbol.iterator`.\nThis can be achieved by using ES6 lib with ES5 target\n(add es6.d.ts to your project) to make it compile.\nCompiled code should work in node 4+, Google Chrome and in some other browsers.\n\n[generics]: ./types/generics.md\n"
  },
  {
    "path": "docs/javascript/closure.md",
    "content": "## Closure\n\nThe best thing that JavaScript ever got was closures. A function in JavaScript has access to any variables defined in the outer scope. Closures are best explained with examples:\n\n```ts\nfunction outerFunction(arg) {\n    var variableInOuterFunction = arg;\n\n    function bar() {\n        console.log(variableInOuterFunction); // Access a variable from the outer scope\n    }\n\n    // Call the local function to demonstrate that it has access to arg\n    bar();\n}\n\nouterFunction(\"hello closure\"); // logs hello closure!\n```\n\nYou can see that the inner function has access to a variable (variableInOuterFunction) from the outer scope. The variables in the outer function have been closed by (or bound in) the inner function. Hence the term **closure**. The concept in itself is simple enough and pretty intuitive.\n\nNow the awesome part: The inner function can access the variables from the outer scope *even after the outer function has returned*. This is because the variables are still bound in the inner function and not dependent on the outer function. Again let's look at an example:\n\n```ts\nfunction outerFunction(arg) {\n    var variableInOuterFunction = arg;\n    return function() {\n        console.log(variableInOuterFunction);\n    }\n}\n\nvar innerFunction = outerFunction(\"hello closure!\");\n\n// Note the outerFunction has returned\ninnerFunction(); // logs hello closure!\n```\n\n### Reason why it's awesome\nIt allows you to compose objects easily e.g. the revealing module pattern:\n\n```ts\nfunction createCounter() {\n    let val = 0;\n    return {\n        increment() { val++ },\n        getVal() { return val }\n    }\n}\n\nlet counter = createCounter();\ncounter.increment();\nconsole.log(counter.getVal()); // 1\ncounter.increment();\nconsole.log(counter.getVal()); // 2\n```\n\nAt a high level it is also what makes something like Node.js possible (don't worry if it doesn't click in your brain right now. It will eventually 🌹):\n\n```ts\n// Pseudo code to explain the concept\nserver.on(function handler(req, res) {\n    loadData(req.id).then(function(data) {\n        // the `res` has been closed over and is available\n        res.send(data);\n    })\n});\n```\n"
  },
  {
    "path": "docs/javascript/equality.md",
    "content": "## Equality\n\nOne thing to be careful about in JavaScript is the difference between `==` and `===`. As JavaScript tries to\nbe resilient against programming errors `==` tries to do type coercion between two variables e.g. converts a\nstring to a number so that you can compare with a number as shown below:\n\n```js\nconsole.log(5 == \"5\"); // true   , TS Error\nconsole.log(5 === \"5\"); // false , TS Error\n```\n\nHowever, the choices JavaScript makes are not always ideal. For example, in the below example the first statement is false\nbecause `\"\"` and `\"0\"` are both strings and are clearly not equal. However, in the second case both `0` and the\nempty string (`\"\"`) are falsy (i.e. behave like `false`) and are therefore equal with respect to `==`. Both statements\nare false when you use `===`.\n\n```js\nconsole.log(\"\" == \"0\"); // false\nconsole.log(0 == \"\"); // true\n\nconsole.log(\"\" === \"0\"); // false\nconsole.log(0 === \"\"); // false\n```\n\n> Note that `string == number` and `string === number` are both compile time errors in TypeScript, so you don't normally need to worry about this.\n\nSimilar to `==` vs. `===`, there is `!=` vs. `!==`\n\nSo ProTip: Always use `===` and `!==` except for null checks, which we cover later.\n\n## Structural Equality \nIf you want to compare two objects for structural equality `==`/`===` are ***not*** sufficient. e.g. \n\n```js\nconsole.log({a:123} == {a:123}); // False\nconsole.log({a:123} === {a:123}); // False\n```\nTo do such checks use the [deep-equal](https://www.npmjs.com/package/deep-equal) npm package e.g. \n\n```js\nimport * as deepEqual from \"deep-equal\";\n\nconsole.log(deepEqual({a:123},{a:123})); // True\n```\n\nHowever, quite commonly you don't need deep checks and all you really need is to check by some `id` e.g. \n\n```ts\ntype IdDisplay = {\n  id: string,\n  display: string\n}\nconst list: IdDisplay[] = [\n  {\n    id: 'foo',\n    display: 'Foo Select'\n  },\n  {\n    id: 'bar',\n    display: 'Bar Select'\n  },\n]\n\nconst fooIndex = list.map(i => i.id).indexOf('foo');\nconsole.log(fooIndex); // 0\n```\n"
  },
  {
    "path": "docs/javascript/null-undefined.md",
    "content": "## Null and Undefined\n\n> [Free youtube video on the subject](https://www.youtube.com/watch?v=kaUfBNzuUAI)\n\nJavaScript (and by extension TypeScript) has two bottom types : `null` and `undefined`. They are *intended* to mean different things:\n\n* Something hasn't been initialized : `undefined`.\n* Something is currently unavailable: `null`.\n\n\n### Checking for either\n\nFact is you will need to deal with both. Interestingly in JavaScript with `==`, `null` and `undefined` are only equal to each other:\n\n```ts\n// Both null and undefined are only `==` to themselves and each other:\nconsole.log(null == null); // true (of course)\nconsole.log(undefined == undefined); // true (of course)\nconsole.log(null == undefined); // true\n\n\n// You don't have to worry about falsy values making through this check\nconsole.log(0 == undefined); // false\nconsole.log('' == undefined); // false\nconsole.log(false == undefined); // false\n```\nRecommend `== null` to check for both `undefined` or `null`. You generally don't want to make a distinction between the two.\n\n```ts\nfunction foo(arg: string | null | undefined) {\n  if (arg != null) {\n    // arg must be a string as `!=` rules out both null and undefined. \n  }\n}\n```\n\n> You could also do `== undefined`, but `== null` is more conventional/shorter.\n\nOne exception, root level `undefined` values which we discuss next.\n\n### Checking for root level undefined\n\nRemember how I said you should use `== null`? Of course you do (cause I just said it ^). Don't use it for root level things. In strict mode if you use `foo` and `foo` is undefined you get a `ReferenceError` **exception** and the whole call stack unwinds.\n\n> You should use strict mode ... and in fact the TS compiler will insert it for you if you use modules ... more on those later in the book so you don't have to be explicit about it :)\n\nSo to check if a variable is defined or not at a *global* level you normally use `typeof`:\n\n```ts\nif (typeof someglobal !== 'undefined') {\n  // someglobal is now safe to use\n  console.log(someglobal);\n}\n```\n\n### Limit explicit use of `undefined`\nBecause TypeScript gives you the opportunity to *document* your structures separately from values instead of stuff like:\n```ts\nfunction foo(){\n  // if Something\n  return {a:1,b:2};\n  // else\n  return {a:1,b:undefined};\n}\n```\nyou should use a type annotation:\n```ts\nfunction foo():{a:number,b?:number}{\n  // if Something\n  return {a:1,b:2};\n  // else\n  return {a:1};\n}\n```\n\n### Node style callbacks\nNode style callback functions (e.g. `(err,somethingElse)=>{ /* something */ }`) are generally called with `err` set to `null` if there isn't an error. You generally just use a truthy check for this anyways:\n\n```ts\nfs.readFile('someFile', 'utf8', (err,data) => {\n  if (err) {\n    // do something\n  } else {\n    // no error\n  }\n});\n```\nWhen creating your own APIs it's *okay* to use `null` in this case for consistency. In all sincerity for your own APIs you should look at promises, in that case you actually don't need to bother with absent error values (you handle them with `.then` vs. `.catch`).\n\n### Don't use `undefined` as a means of denoting *validity*\n\nFor example an awful function like this:\n\n```ts\nfunction toInt(str: string) {\n  return str ? parseInt(str) : undefined;\n}\n```\ncan be much better written like this:\n```ts\nfunction toInt(str: string): { valid: boolean, int?: number } {\n  const int = parseInt(str);\n  if (isNaN(int)) {\n    return { valid: false };\n  }\n  else {\n    return { valid: true, int };\n  }\n}\n```\n\n### JSON and serialization\n\nThe JSON standard has support for encoding `null` but not `undefined`. When JSON-encoding an object with an attribute that is `null`, the attribute will be included with its null value, whereas an attribute with an `undefined` value will be excluded entirely.\n\n```ts\nJSON.stringify({willStay: null, willBeGone: undefined}); // {\"willStay\":null}\n```\n\nAs a result, JSON-based databases may support `null` values but not `undefined` values. Since attributes set to `null` are encoded, you can transmit the intent to clear an attribute by setting its value to `null` before encoding and transmitting the object to a remote store.\n\nSetting attribute values to undefined can save on storage and transmission costs, as the attribute names will not be encoded. However, this can complicate the semantics of clearing values vs. absent values.\n\n### Final thoughts\nTypeScript team doesn't use `null` : [TypeScript coding guidelines](https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines#null-and-undefined) and it hasn't caused any problems. Douglas Crockford thinks [`null` is a bad idea](https://www.youtube.com/watch?v=PSGEjv3Tqo0&feature=youtu.be&t=9m21s) and we should all just use `undefined`.\n\nHowever, NodeJS style code bases uses `null` for Error arguments as standard as it denotes `Something is currently unavailable`. I personally don't care to distinguish between the two as most projects use libraries with differing opinions and just rule out both with `== null`.\n"
  },
  {
    "path": "docs/javascript/number.md",
    "content": "## Number\nWhenever you are handling numbers in any programming language you need to be aware of the idiosyncrasies of how the language handles numbers. Here are a few critical pieces of information about numbers in JavaScript that you should be aware of.\n\n### Core Type\nJavaScript has only one number type. It is a double-precision 64-bit `Number`. Below we discuss its limitations along with a recommended solution.\n\n### Decimal\nFor those familiar with doubles / float in other languages, you would know that binary floating point numbers *do not* map correctly to Decimal numbers. A trivial (and famous) example with JavaScript's built in numbers is shown below:\n\n```js\nconsole.log(.1 + .2); // 0.30000000000000004\n```\n\n> For true decimal math use `big.js` mentioned below.\n\n### Integer\nThe integer limits represented by the built in number type are `Number.MAX_SAFE_INTEGER` and `Number.MIN_SAFE_INTEGER`.\n\n```js\nconsole.log({max: Number.MAX_SAFE_INTEGER, min: Number.MIN_SAFE_INTEGER});\n// {max: 9007199254740991, min: -9007199254740991}\n```\n\n**Safe** in this context refers to the fact that the value *cannot be the result of a rounding error*.\n\nThe unsafe values are `+1 / -1` away from these safe values and any amount of addition / subtraction will *round* the result.\n\n```js\nconsole.log(Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2); // true!\nconsole.log(Number.MIN_SAFE_INTEGER - 1 === Number.MIN_SAFE_INTEGER - 2); // true!\n\nconsole.log(Number.MAX_SAFE_INTEGER);      // 9007199254740991\nconsole.log(Number.MAX_SAFE_INTEGER + 1);  // 9007199254740992 - Correct\nconsole.log(Number.MAX_SAFE_INTEGER + 2);  // 9007199254740992 - Rounded!\nconsole.log(Number.MAX_SAFE_INTEGER + 3);  // 9007199254740994 - Rounded - correct by luck\nconsole.log(Number.MAX_SAFE_INTEGER + 4);  // 9007199254740996 - Rounded!\n```\n\nTo check safety you can use ES6 `Number.isSafeInteger`:\n\n```js\n// Safe value\nconsole.log(Number.isSafeInteger(Number.MAX_SAFE_INTEGER)); // true\n\n// Unsafe value\nconsole.log(Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 1)); // false\n\n// Because it might have been rounded to it due to overflow\nconsole.log(Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 10)); // false\n```\n\n> JavaScript will eventually get [BigInt](https://developers.google.com/web/updates/2018/05/bigint) support. For now, if you want arbitrary precision integer math use `big.js` mentioned below.\n\n### big.js\nWhenever you use math for financial calculations (e.g. GST calculation, money with cents, addition etc) use a library like [big.js](https://github.com/MikeMcl/big.js/) which is designed for\n* Perfect decimal math\n* Safe out of bound integer values\n\nInstallation is simple:\n```bash\nnpm install big.js @types/big.js\n```\n\nQuick Usage example:\n\n```js\nimport { Big } from 'big.js';\n\nexport const foo = new Big('111.11111111111111111111');\nexport const bar = foo.plus(new Big('0.00000000000000000001'));\n\n// To get a number:\nconst x: number = Number(bar.toString()); // Loses the precision\n```\n\n> Do not use this library for math used for UI / performance intensive purposes e.g charts, canvas drawing etc.\n\n### NaN\nWhen some number calculation is not representable by a valid number, JavaScript returns a special `NaN` value. A  classic example is imaginary numbers:\n\n```js\nconsole.log(Math.sqrt(-1)); // NaN\n```\n\nNote: Equality checks **don't** work on `NaN` values. Use `Number.isNaN` instead:\n\n```js\n// Don't do this\nconsole.log(NaN === NaN); // false!!\n\n// Do this\nconsole.log(Number.isNaN(NaN)); // true\n```\n\n### Infinity\nThe outer bounds of values representable in Number are available as static `Number.MAX_VALUE` and `-Number.MAX_VALUE` values.\n\n```js\nconsole.log(Number.MAX_VALUE);  // 1.7976931348623157e+308\nconsole.log(-Number.MAX_VALUE); // -1.7976931348623157e+308\n```\n\nValues outside the range where precision isn't changed are clamped to these limits e.g.\n\n```js\nconsole.log(Number.MAX_VALUE + 1 == Number.MAX_VALUE);   // true!\nconsole.log(-Number.MAX_VALUE - 1 == -Number.MAX_VALUE); // true!\n```\n\nValues outside the range where precision is changed resolve to special values `Infinity`/`-Infinity` e.g.\n\n```js\nconsole.log(Number.MAX_VALUE + 1e292);  // Infinity\nconsole.log(-Number.MAX_VALUE - 1e292); // -Infinity\n```\n\nOf-course, these special infinity values also show up with arithmetic that requires it e.g.\n\n```js\nconsole.log( 1 / 0); // Infinity\nconsole.log(-1 / 0); // -Infinity\n```\n\nYou can use these `Infinity` values manually or using static members of the `Number` class as shown below:\n\n```js\nconsole.log(Number.POSITIVE_INFINITY === Infinity);  // true\nconsole.log(Number.NEGATIVE_INFINITY === -Infinity); // true\n```\n\nFortunately comparison operators (`<` / `>`) work reliably on infinity values:\n\n```js\nconsole.log( Infinity >  1); // true\nconsole.log(-Infinity < -1); // true\n```\n\n### Infinitesimal\n\nThe smallest non-zero value representable in Number is available as static `Number.MIN_VALUE`\n\n```js\nconsole.log(Number.MIN_VALUE);  // 5e-324\n```\n\nValues smaller than `MIN_VALUE` (\"underflow values\") are converted to 0.\n\n```js\nconsole.log(Number.MIN_VALUE / 10);  // 0\n```\n\n> Further intuition: Just like values bigger than `Number.MAX_VALUE` get clamped to INFINITY, values smaller than `Number.MIN_VALUE` get clamped to `0`.\n"
  },
  {
    "path": "docs/javascript/recap.md",
    "content": "# Your JavaScript is TypeScript\n\nThere were (and will continue to be) a lot of competitors in *Some syntax* to *JavaScript* compilers. TypeScript is different from them in that *Your JavaScript is TypeScript*. Here's a diagram:\n\n![JavaScript is TypeScript](https://raw.githubusercontent.com/basarat/typescript-book/master/images/venn.png)\n\nHowever, it does mean that *you need to learn JavaScript* (the good news is *you **only** need to learn JavaScript*). TypeScript is just standardizing all the ways you provide *good documentation* on JavaScript.\n\n* Just giving you a new syntax doesn't help catch bugs - but might help you write cleaner / less bugs (e.g. CoffeeScript).\n* Creating a new language abstracts you too far from your runtimes and communities - but might help on-board you easier if its an already familiar flavour (e.g. Dart - closer for Java / C# devs).\n\nTypeScript is just JavaScript with docs.\n\n> JSNext is open to interpretation - not everything proposed for the next version of JS actually makes it to browsers. TypeScript only adds support for proposals once they reach [stage 3](https://tc39.es/process-document/).\n\n## Making JavaScript Better\n\nTypeScript will try to protect you from portions of JavaScript that never worked (so you don't need to remember this stuff):\n\n```ts\n[] + []; // JavaScript will give you \"\" (which makes little sense), TypeScript will error\n\n//\n// other things that are nonsensical in JavaScript\n// - don't give a runtime error (making debugging hard)\n// - but TypeScript will give a compile time error (making debugging unnecessary)\n//\n{} + []; // JS : 0, TS Error\n[] + {}; // JS : \"[object Object]\", TS Error\n{} + {}; // JS : NaN or [object Object][object Object] depending upon browser, TS Error\n\"hello\" - 1; // JS : NaN, TS Error\n\nfunction add(a,b) {\n  return\n    a + b; // JS : undefined, TS Error 'unreachable code detected'\n}\n```\n\nEssentially TypeScript is linting JavaScript. Just doing a better job at it than other linters that don't have *type information*.\n\n## You still need to learn JavaScript\n\nThat said TypeScript is very pragmatic about the fact that *you do write JavaScript* so there are some things about JavaScript that you still need to know in order to not be caught off-guard. Let's discuss them next.\n\n> Note: TypeScript is a superset of JavaScript. Just with documentation that can actually be used by compilers / IDEs ;)\n"
  },
  {
    "path": "docs/javascript/references.md",
    "content": "## References\n\nBeyond literals, any Object in JavaScript (including functions, arrays, regexp etc) are references. This means the following\n\n### Mutations are across all references\n\n```js\nvar foo = {};\nvar bar = foo; // bar is a reference to the same object\n\nfoo.baz = 123;\nconsole.log(bar.baz); // 123\n```\n\n### Equality is for references\n\n```js\nvar foo = {};\nvar bar = foo; // bar is a reference\nvar baz = {}; // baz is a *new object* distinct from `foo`\n\nconsole.log(foo === bar); // true\nconsole.log(foo === baz); // false\n```\n"
  },
  {
    "path": "docs/javascript/this.md",
    "content": "## this\n\nAny access to `this` keyword within a function is controlled by how the function is actually called. It is commonly referred to as the “calling context.”\n\nHere is an example:\n\n```ts\nfunction foo() {\n  console.log(this);\n}\n\nfoo(); // logs out the global e.g. `window` in browsers\nlet bar = {\n  foo\n}\nbar.foo(); // Logs out `bar` as `foo` was called on `bar`\n```\n\nSo be mindful of your usage of `this`. If you want to disconnect `this` in a class from the calling context use an arrow function, [more on that later][arrow].\n\n[arrow]:../arrow-functions.md\n"
  },
  {
    "path": "docs/javascript/truthy.md",
    "content": "## Truthy\n\nJavaScript has a concept of `truthy` i.e. things that evaluate like `true` would in certain positions (e.g. `if` conditions and the boolean `&&` `||` operators). The following things are truthy in JavaScript. An example is any number other than `0` e.g.\n\n```ts\nif (123) { // Will be treated like `true`\n  console.log('Any number other than 0 is truthy');\n}\n```\n\nSomething that isn't truthy is called `falsy`.\n\nHere's a handy table for your reference.\n\n| Variable Type   | When it is *falsy*       | When it is *truthy*      |\n|-----------------|--------------------------|--------------------------|\n| `boolean`       | `false`                  | `true`                   |\n| `string`        | `''` (empty string)      | any other string         |\n| `number`        | `0`  `NaN`               | any other number         |\n| `null`          | always                   | never                    |\n| `undefined`     | always                   | never                    |\n| Any other Object including empty ones like `{}`,`[]` | never | always |\n\n\n### Being explicit\n\n> The `!!` pattern\n\nQuite commonly it helps to be explicit that the intent is to treat the value as a `boolean` and convert it into a *true boolean* (one of `true`|`false`). You can easily convert values to a true boolean by prefixing it with `!!` e.g. `!!foo`. Its just `!` used *twice*. The first `!` converts the variable (in this case `foo`) to a boolean but inverts the logic (*truthy* -`!`> `false`, *falsy* -`!`> `true`). The second one toggles it again to match the nature of the original object (e.g. *truthy* -`!`> `false` -`!`> `true`).\n\nIt is common to use this pattern in lots of places e.g.\n\n```js\n// Direct variables\nconst hasName = !!name;\n\n// As members of objects\nconst someObj = {\n  hasName: !!name\n}\n\n// e.g. in ReactJS JSX\n{!!someName && <div>{someName}</div>}\n```\n"
  },
  {
    "path": "docs/jsx/others.md",
    "content": "# Non React JSX\n\n[![DesignTSX](https://raw.githubusercontent.com/basarat/typescript-book/master/images/designtsx-banner.png)](https://designtsx.com)\n\nTypeScript provides you with the ability to use something other than React with JSX in a type safe manner. The following lists the customizability points, but note that this is for advanced UI framework authors:\n\n* You can disable `react` style emit by using `\"jsx\" : \"preserve\"` option. This means that JSX is emitted *as is* and then you can use your own custom transpiler to transpile the JSX portions.\n* Using the `JSX` global module:\n    * You can control what HTML tags are available and how they are type checked by customizing the `JSX.IntrinsicElements` interface members.\n    * When using components:\n        * You can control which `class` must be inherited by components by customizing the default `interface ElementClass extends React.Component<any, any> { }` declaration.\n        * You can control which property is used to type check the attributes (the default is `props`) by customizing the `declare module JSX { interface ElementAttributesProperty { props: {}; } }` declaration.\n\n## `jsxFactory`\n\nPassing `--jsxFactory <JSX factory Name>` along with `--jsx react` allows for using a different JSX factory from the default `React`.\n\nThe new factory name will be used to call `createElement` functions.\n\n### Example\n\n```ts\nimport {jsxFactory} from \"jsxFactory\";\n\nvar div = <div>Hello JSX!</div>\n```\n\nCompiled with:\n\n```shell\ntsc --jsx react --reactNamespace jsxFactory --m commonJS\n```\n\nResults in:\n\n```js\n\"use strict\";\nvar jsxFactory_1 = require(\"jsxFactory\");\nvar div = jsxFactory_1.jsxFactory.createElement(\"div\", null, \"Hello JSX!\");\n```\n\n## `jsx` pragma\n\nYou can even specify a different `jsxFactory` per file using `jsxPragma` e.g. \n\n\n```js\n/** @jsx jsxFactory */\nimport {jsxFactory} from \"jsxFactory\";\n\nvar div = <div>Hello JSX!</div>\n```\n\nWith `--jsx react` this file will emit to use the factory specfied in the jsx pragma: \n```js\n\"use strict\";\nvar jsxFactory_1 = require(\"jsxFactory\");\nvar div = jsxFactory_1.jsxFactory.createElement(\"div\", null, \"Hello JSX!\");\n```\n"
  },
  {
    "path": "docs/jsx/react.md",
    "content": "# React JSX\n\n> [Free series of youtube videos on React / TypeScript best practices](https://www.youtube.com/watch?v=7EW67MqgJvs&list=PLYvdvJlnTOjHNayH7MukKbSJ6PueUNkkG)\n\n> [PRO Egghead course on TypeScript and React](https://egghead.io/courses/use-typescript-to-develop-react-applications)\n\n[![DesignTSX](https://raw.githubusercontent.com/basarat/typescript-book/master/images/designtsx-banner.png)](https://designtsx.com)\n\n## Setup\n\nOur [browser quickstart already sets you up to develop react applications](../quick/browser.md). Here are the key highlights.\n\n* Use files with the extension `.tsx` (instead of `.ts`).\n* Use `\"jsx\" : \"react\"` in your `tsconfig.json`'s `compilerOptions`.\n* Install the definitions for JSX and React into your project : (`npm i -D @types/react @types/react-dom`).\n* Import react into your `.tsx` files (`import * as React from \"react\"`).\n\n## HTML Tags vs. Components\n\nReact can either render HTML tags (strings) or React components. The JavaScript emit for these elements is different (`React.createElement('div')` vs. `React.createElement(MyComponent)`). The way this is determined is by the *case* of the *first* letter. `foo` is treated as an HTML tag and `Foo` is treated as a component.\n\n## Type Checking\n\n### HTML Tags\n\nAn HTML Tag `foo` is to be of the type `JSX.IntrinsicElements.foo`. These types are already defined for all the major tags in a file `react-jsx.d.ts` which we had you install as a part of the setup. Here is a sample of the  the contents of the file:\n\n```ts\ndeclare module JSX {\n    interface IntrinsicElements {\n        a: React.HTMLAttributes;\n        abbr: React.HTMLAttributes;\n        div: React.HTMLAttributes;\n        span: React.HTMLAttributes;\n\n        /// so on ...\n    }\n}\n```\n\n### Function Components\n\nYou can define function components simply with the `React.FunctionComponent` interface e.g.\n\n```ts\ntype Props = {\n  foo: string;\n}\nconst MyComponent: React.FunctionComponent<Props> = (props) => {\n    return <span>{props.foo}</span>\n}\n\n<MyComponent foo=\"bar\" />\n```\n\n### Void Function Components\n\nAs of [@types/react PR #46643](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/46643), you can use a new `React.VoidFunctionComponent` or `React.VFC` type if you wish to declare that a component does not take `children`. This is an interim solution until the next major version of the type defs (where VoidFunctionComponent will be deprecated and FunctionComponent will by default accept no children).\n\n```ts\ntype Props = { \n  foo: string \n}\n// OK now, in future, error\nconst FunctionComponent: React.FunctionComponent<Props> = ({ foo, children }: Props) => {\n    return <div>{foo} {children}</div>; // OK\n};\n// Error now (children not support), in future, deprecated\nconst VoidFunctionComponent: React.VoidFunctionComponent<Props> = ({ foo, children }) => {\n    return <div>{foo}{children}</div>; \n};\n```\n\n### Class Components\n\nComponents are type checked based on the `props` property of the component. This is modeled after how JSX is transformed i.e. the attributes become the `props` of the component.\n\nThe `react.d.ts` file defines the `React.Component<Props,State>` class which you should extend in your own class providing your own `Props` and `State` interfaces. This is demonstrated below:\n\n```ts\ntype Props = {\n  foo: string;\n}\nclass MyComponent extends React.Component<Props, {}> {\n    render() {\n        return <span>{this.props.foo}</span>\n    }\n}\n\n<MyComponent foo=\"bar\" />\n```\n\n### React JSX Tip: Interface for renderable\n\nReact can render a few things like `JSX` or `string`. These are all consolidated into the type `React.ReactNode` so use it for when you want to accept renderables e.g.\n\n```ts\ntype Props = {\n  header: React.ReactNode;\n  body: React.ReactNode;\n}\nclass MyComponent extends React.Component<Props, {}> {\n    render() {\n        return <div>\n            {this.props.header}\n            {this.props.body}\n        </div>;\n    }\n}\n\n<MyComponent header={<h1>Header</h1>} body={<i>body</i>} />\n```\n\n### React JSX Tip: Accept an instance of a Component\n\nThe react type definitions provide `React.ReactElement<T>` to allow you to annotate the result of a `<T/>` class component instantiation. e.g.\n\n```js\nclass MyAwesomeComponent extends React.Component {\n  render() {\n    return <div>Hello</div>;\n  }\n}\n\nconst foo: React.ReactElement<MyAwesomeComponent> = <MyAwesomeComponent />; // Okay\nconst bar: React.ReactElement<MyAwesomeComponent> = <NotMyAwesomeComponent />; // Error!\n```\n\n> Of course you can use this as a function argument annotation and even React component prop member.\n\n### React JSX Tip: Accept a *component* that can act on props and be rendered using JSX\n\nThe type `React.Component<Props>` consolidates `React.ComponentClass<P> | React.StatelessComponent<P>` so you can accept *something* that takes type `Props` and renders it using JSX e.g.\n\n```ts\nconst X: React.Component<Props> = foo; // from somewhere\n\n// Render X with some props:\n<X {...props}/>;\n```\n\n### React JSX Tip: Generic components\n\nIt works exactly as expected. Here is an example:\n\n```ts\n/** A generic component */\ntype SelectProps<T> = { items: T[] }\nclass Select<T> extends React.Component<SelectProps<T>, any> { }\n\n/** Usage */\nconst Form = () => <Select<string> items={['a','b']} />;\n```\n\n### Generic functions\n\nSomething like the following works fine:\n\n```ts\nfunction foo<T>(x: T): T { return x; }\n```\n\nHowever, using an arrow generic function will not:\n\n```ts\nconst foo = <T>(x: T) => x; // ERROR : unclosed `T` tag\n```\n\n**Workaround**: Use `extends` on the generic parameter to hint the compiler that it's a generic, e.g.:\n\n```ts\nconst foo = <T extends unknown>(x: T) => x;\n```\n\n### React Tip: Strongly Typed Refs \nYou basically initialize a variable as a union of the ref and `null` and then initialize it as as callback  e.g. \n\n```ts\nclass Example extends React.Component {\n  example() {\n    // ... something\n  }\n  \n  render() { return <div>Foo</div> }\n}\n\n\nclass Use {\n  exampleRef: Example | null = null; \n  \n  render() {\n    return <Example ref={exampleRef => this.exampleRef = exampleRef } />\n  }\n}\n```\n\nAnd the same with ref's for native elements e.g. \n\n```ts\nclass FocusingInput extends React.Component<{ value: string, onChange: (value: string) => any }, {}>{\n  input: HTMLInputElement | null = null;\n    \n  render() {\n    return (\n      <input\n        ref={(input) => this.input = input}\n        value={this.props.value}\n        onChange={(e) => { this.props.onChange(e.target.value) } }\n        />\n      );\n    }\n    focus() {\n      if (this.input != null) { this.input.focus() }\n    }\n}\n```\n\n### Type Assertions\n\nUse `as Foo` syntax for type assertions as we [mentioned before](../types/type-assertion.md#as-foo-vs-foo).\n\n## Default Props\n\n* Stateful components with default props: You can tell TypeScript that a property will be provided externally (by React) by using a *null assertion* operator (this isn't ideal but is the simplest minimum *extra code* solution I could think of).\n\n```tsx\nclass Hello extends React.Component<{\n  /**\n   * @default 'TypeScript'\n   */\n  compiler?: string,\n  framework: string\n}> {\n  static defaultProps = {\n    compiler: 'TypeScript'\n  }\n  render() {\n    const compiler = this.props.compiler!;\n    return (\n      <div>\n        <div>{compiler}</div>\n        <div>{this.props.framework}</div>\n      </div>\n    );\n  }\n}\n\nReactDOM.render(\n  <Hello framework=\"React\" />, // TypeScript React\n  document.getElementById(\"root\")\n);\n```\n\n* SFC with default props: Recommend leveraging simple JavaScript patterns as they work well with TypeScript's type system e.g.\n\n```tsx\nconst Hello: React.SFC<{\n  /**\n   * @default 'TypeScript'\n   */\n  compiler?: string,\n  framework: string\n}> = ({\n  compiler = 'TypeScript', // Default prop\n  framework\n}) => {\n    return (\n      <div>\n        <div>{compiler}</div>\n        <div>{framework}</div>\n      </div>\n    );\n  };\n\n\nReactDOM.render(\n  <Hello framework=\"React\" />, // TypeScript React\n  document.getElementById(\"root\")\n);\n```\n\n## Declaring a webcomponent\n\nIf you are using a web component the default React type definitions (`@types/react`) will not know about it. But you can declare it easily e.g. to declare a webcomponent called `my-awesome-slider` that takes Props `MyAwesomeSliderProps` you would: \n\n```tsx\ndeclare global {\n  namespace JSX {\n    interface IntrinsicElements {\n      'my-awesome-slider': MyAwesomeSliderProps;\n    }\n\n    interface MyAwesomeSliderProps extends React.Attributes {\n      name: string;\n    }\n  }\n}\n```\n\nNow you can use it in TSX:\n\n```tsx\n<my-awesome-slider name='amazing'/>\n```\n"
  },
  {
    "path": "docs/jsx/tsx.md",
    "content": "# JSX Support\n\n[![DesignTSX](https://raw.githubusercontent.com/basarat/typescript-book/master/images/designtsx-banner.png)](https://designtsx.com)\n\nTypeScript supports JSX transpilation and code analysis. If you are unfamiliar with JSX here is an excerpt from the [official website](https://facebook.github.io/jsx/):\n\n> JSX is an XML-like syntax extension to ECMAScript without any defined semantics. It's NOT intended to be implemented by engines or browsers. It's NOT a proposal to incorporate JSX into the ECMAScript spec itself. It's intended to be used by various preprocessors (transpilers) to transform these tokens into standard ECMAScript.\n\nThe motivation behind JSX is to allow users to write HTML like views *in JavaScript* so that you can:\n\n* Have the view Type Checked by the same code that is going to check your JavaScript\n* Have the view be aware of the context it is going to operate under (i.e. strengthen the *controller-view* connection in traditional MVC).\n* Reuse JavaScript patterns for HTML maintenance e.g. `Array.prototype.map`, `?:`, `switch` etc instead of creating new (and probably poorly typed) alternatives.\n\nThis decreases the chances of errors and increases the maintainability of your user interfaces. The main consumer of JSX at this point is [ReactJS from facebook](http://facebook.github.io/react/). This is the usage of JSX that we will discuss here.\n"
  },
  {
    "path": "docs/let.md",
    "content": "### let\n\n`var` Variables in JavaScript are *function scoped*. This is different from many other languages (C# / Java etc.) where the variables are *block scoped*. If you bring a *block scoped* mindset to JavaScript, you would expect the following to print `123`, instead it will print `456`:\n\n```ts\nvar foo = 123;\nif (true) {\n    var foo = 456;\n}\nconsole.log(foo); // 456\n```\nThis is because `{` does not create a new *variable scope*. The variable `foo` is the same inside the if *block* as it is outside the if block. This is a common source of errors in JavaScript programming. This is why TypeScript (and ES6) introduces the `let` keyword to allow you to define variables with true *block scope*. That is if you use `let` instead of `var` you get a true unique element disconnected from what you might have defined outside the scope. The same example is demonstrated with `let`:\n\n```ts\nlet foo = 123;\nif (true) {\n    let foo = 456;\n}\nconsole.log(foo); // 123\n```\n\nAnother place where `let` would save you from errors is loops.\n```ts\nvar index = 0;\nvar array = [1, 2, 3];\nfor (let index = 0; index < array.length; index++) {\n    console.log(array[index]);\n}\nconsole.log(index); // 0\n```\nIn all sincerity we find it better to use `let` whenever possible as it leads to fewer surprises for new and existing multi-lingual developers.\n\n#### Functions create a new scope\nSince we mentioned it, we'd like to demonstrate that functions create a new variable scope in JavaScript. Consider the following:\n\n```ts\nvar foo = 123;\nfunction test() {\n    var foo = 456;\n}\ntest();\nconsole.log(foo); // 123\n```\nThis behaves as you would expect. Without this it would be very difficult to write code in JavaScript.\n\n#### Generated JS\nThe JS generated by TypeScript is simple renaming of the `let` variable if a similar name already exists in the surrounding scope. E.g. the following is generated as is with a simple replacement of `let` with `var`:\n\n```ts\nif (true) {\n    let foo = 123;\n}\n\n// becomes //\n\nif (true) {\n    var foo = 123;\n}\n```\nHowever, if the variable name is already taken by the surrounding scope then a new variable name is generated as shown (notice `foo_1`):\n\n```ts\nvar foo = '123';\nif (true) {\n    let foo = 123;\n}\n\n// becomes //\n\nvar foo = '123';\nif (true) {\n    var foo_1 = 123; // Renamed\n}\n```\n\n#### Switch\nYou can wrap your `case` bodies in `{}` to reuse variable names reliably in different `case` statement as shown below:\n\n```ts\nswitch (name) {\n    case 'x': {\n        let x = 5;\n        // ...\n        break;\n    }\n    case 'y': {\n        let x = 10;\n        // ...\n        break;\n    }\n}\n```\n\n#### let in closures\nA common programming interview question for a JavaScript developer is what is the log of this simple file:\n\n```ts\nvar funcs = [];\n// create a bunch of functions\nfor (var i = 0; i < 3; i++) {\n    funcs.push(function() {\n        console.log(i);\n    })\n}\n// call them\nfor (var j = 0; j < 3; j++) {\n    funcs[j]();\n}\n```\nOne would have expected it to be `0,1,2`. Surprisingly it is going to be `3` for all three functions. Reason is that all three functions are using the variable `i` from the outer scope and at the time we execute them (in the second loop) the value of `i` will be `3` (that's the termination condition for the first loop).\n\nA fix would be to create a new variable in each loop specific to that loop iteration. As we've learnt before we can create a new variable scope by creating a new function and immediately executing it (i.e. the IIFE pattern from classes `(function() { /* body */ })();`) as shown below:\n\n```ts\nvar funcs = [];\n// create a bunch of functions\nfor (var i = 0; i < 3; i++) {\n    (function() {\n        var local = i;\n        funcs.push(function() {\n            console.log(local);\n        })\n    })();\n}\n// call them\nfor (var j = 0; j < 3; j++) {\n    funcs[j]();\n}\n```\nHere the functions close over (hence called a `closure`) the *local* variable (conveniently named `local`) and use that instead of the loop variable `i`.\n\n> Note that closures come with a performance impact (they need to store the surrounding state).\n\nThe ES6 `let` keyword in a loop would have the same behavior as the previous example:\n\n```ts\nvar funcs = [];\n// create a bunch of functions\nfor (let i = 0; i < 3; i++) { // Note the use of let\n    funcs.push(function() {\n        console.log(i);\n    })\n}\n// call them\nfor (var j = 0; j < 3; j++) {\n    funcs[j]();\n}\n```\n\nUsing a `let` instead of `var` creates a variable `i` unique to each loop iteration.\n\n#### Summary\n`let` is extremely useful to have for the vast majority of code. It can greatly enhance your code readability and decrease the chance of a programming error.\n\n\n\n[](https://github.com/olov/defs/blob/master/loop-closures.md)\n"
  },
  {
    "path": "docs/npm/index.md",
    "content": "# NPM \n\n> Fun fact `npm` is [not an acronym](https://twitter.com/npmjs/status/347057301401763840) so it doesn't expand to anything, but among friends it is commonly called `node package manager`.\n\n`npm` is a binary that comes with default `node` installations used to manage community shared JavaScript / TypeScript packages.\n\n\n* NPM packages are hosted at (and installed from) https://www.npmjs.com/ (the ☁️).\n\n## Quick common setup\n\n* npm packages are configured using `package.json` file. You can generate a quick file using `npm init -y`.\n* packages get installed into a `./node_modules` folder. You normally have this folder in your `.gitignore`.\n\n> Even though you might be building an application, having a `package.json` essentially makes your project a package as well. So the terms your `project | package` can be used interchangeably.\n\nWhen you checkout someone's (your team's) package, it will have a `package.json` that will list the dependencies you need to run the project. You simply run `npm install` and npm will bring them down from the cloud ☁️.\n \n## Installing a package\nYou can run `npm install <something>`. Most people will use the shorthand `npm i <something>` e.g. \n\n```ts\n// Install react\nnpm i react\n```\n\n> This will also automatically add `react` into your `package.json`'s `dependencies`.\n\n## Installing a devDependency\n`devDependencies` are dependencies that are only required during *development* if your project and not required after deployment. \n\n`typescript` is common in `devDependencies` as its only required to build `.ts -> .js`. You normally deploy the built `.js` files:\n\n* into production  \n* OR for consumption by other other npm packages\n\n## Security\nThe public `npm` packages are scanned by security team worldwide and issues get reported to npm team. They then release security advisories detailing the issue and potential fixes. Commonly the fix is simply updating the package. \n\nYou can run an audit on your node project by simply running `npm audit`. This will highlight any vulnerabilities that might exist in the package / dependencies of the package. e.g. \n\n```\n┌───────────────┬──────────────────────────────────────────────────────────────┐\n│ Low           │ Regular Expression Denial of Service                         │\n├───────────────┼──────────────────────────────────────────────────────────────┤\n│ Package       │ debug                                                        │\n├───────────────┼──────────────────────────────────────────────────────────────┤\n│ Dependency of │ jest [dev]                                                   │\n├───────────────┼──────────────────────────────────────────────────────────────┤\n│ Path          │ jest > jest-cli > istanbul-lib-source-maps > debug           │\n├───────────────┼──────────────────────────────────────────────────────────────┤\n│ More info     │ https://nodesecurity.io/advisories/534                       │\n└───────────────┴──────────────────────────────────────────────────────────────┘\n```\n\nNote that commonly the issues are found in *development* dependencies (e.g. jest in this case). Since these aren't are a part of your production deployments, most likely your production application is not vulnerable. But still good practice to keep vulnerabilities to `0`.\n\nSimply add `npm audit` (the command exist with error code `1` in case of error) as a part of your deployment to ensure the projects stay up to date.\n\n## NPM Scripts \n\n### What is with `--` in scripts \nYou can build a base script with a limited set of command line arguments e.g. here is a script target that runs `tsc` for the TypeScript compiler: \n\n```json\n{\n  \"scripts\": {\n    \"build\": \"tsc -p .\"\n  }\n}\n```\n\nYou can create a `build:watch` target to run `tsc -p . -w` or alternatively asking npm to run `build` with the additional `-w` flag like so: \n\n```json\n{\n  \"scripts\": {\n    \"build\": \"tsc -p .\",\n    \"build:watch\": \"npm run build -- -w\"\n  }\n}\n```\nYou can pass in as many flags as you want after `--` e.g. in the following example `build:more` has the same effect as `something --foo -f -d --bar`\n\n```json\n{\n  \"scripts\": {\n    \"build\": \"something --foo\",\n    \"build:more\": \"npm run build -- -f -d --bar\"\n  }\n}\n```\n\n## Public vs. Private packages\nYou don't need this when *using* any of the common public npm packages. Just know its there for enterprise / commercial customers.\n\n### Public packages\n* Packages are public by default. \n* Anyone can deploy a package to npm. \n* You just need an account (which you can get for free).\n \nNo one needs an account to download a public package. \n\nThis free sharing of packages is one of the key reasons of success for npm 🌹.\n\n### Private packages \n\nIf you want a private package for your company / team / enterprise you need to sign up to a paid plan, details here : https://www.npmjs.com/pricing\n\nOf-course you need an account with the right permissions to download a private package.\n "
  },
  {
    "path": "docs/options/intro.md",
    "content": "# Convenience vs. Soundness\n\nThere are a few things that TypeScript prevents you from doing out of the box e.g. using a variable that *isn't ever declared* (of course you can use a *declaration file* for external systems).\n\nThat said, traditionally programming languages have a hard boundary between what is and isn't allowed by the type system. TypeScript is different in that it gives you control over where you put the slider. This is really to allow you to use the JavaScript you know and love with as much safety as **you** want. There are lots of compiler options to control exactly this slider so let's have a look.\n\n## Boolean Options\n\n`compilerOptions` that are `boolean` can be specified as `compilerOptions` in `tsconfig.json`:\n\n```json\n{\n    \"compilerOptions\": {\n        \"someBooleanOption\": true\n    }\n}\n```\n\nor on the command line\n\n```sh\ntsc --someBooleanOption\n```\n\n> All of these are `false` by default.\n\nClick [here](https://www.typescriptlang.org/docs/handbook/compiler-options.html) to see all compiler options.\n"
  },
  {
    "path": "docs/options/noImplicitAny.md",
    "content": "# noImplicitAny\n\nThere are some things that cannot be inferred or inferring them might result in unexpected errors. A fine example is function arguments. If you don't annotate them, its unclear what should and shouldn't be valid e.g.\n\n```ts\nfunction log(someArg) {\n  sendDataToServer(someArg);\n}\n\n// What arg is valid and what isn't?\nlog(123);\nlog('hello world');\n```\n\nSo if you don't annotate some function argument, TypeScript assumes `any` and moves on. This essentially turns off type checking for such cases, which is what a JavaScript dev would expect. But this can catch people that want high safety off guard. Hence there is an option, `noImplicitAny`, that when switched on will flag the cases where the type cannot be inferred e.g.\n\n```ts\nfunction log(someArg) { // Error : someArg has an implicit `any` type\n  sendDataToServer(someArg);\n}\n```\n\nOf course you can then go ahead and annotate:\n\n```ts\nfunction log(someArg: number) {\n  sendDataToServer(someArg);\n}\n```\n\nAnd if you truly want *zero safety* you can mark it *explicitly* as `any`:\n\n```ts\nfunction log(someArg: any) {\n  sendDataToServer(someArg);\n}\n```\n"
  },
  {
    "path": "docs/options/strictNullChecks.md",
    "content": "# `strictNullChecks`\n\nBy default `null` and `undefined` are assignable to all types in TypeScript e.g.\n\n```ts\nlet foo: number = 123;\nfoo = null; // Okay\nfoo = undefined; // Okay\n```\n\nThis is modelled after how a lot of people write JavaScript. However, like all things, TypeScript allows you to be *explicit* about what *can and cannot be* assigned a `null` or `undefined`.\n\nIn strict null checking mode, `null` and `undefined` are different:\n\n```ts\nlet foo = undefined;\nfoo = null; // NOT Okay\n```\n\nLet's say we have a `Member` interface:\n\n```ts\ninterface Member {\n  name: string,\n  age?: number\n}\n```\n\nNot every `Member` will provide their age, so `age` is an optional property, meaning the value of `age` may or may not be `undefined`.\n\n`undefined` is the root of all evil. It often leads to runtime errors. It is easy to write code that will throw `Error` at runtime:\n\n```ts\ngetMember()\n  .then(member: Member => {\n    const stringifyAge = member.age.toString() // Cannot read property 'toString' of undefined\n  })\n```\n\nBut in strict null checking mode, this error will be caught at compile time:\n\n```ts\ngetMember()\n  .then(member: Member => {\n    const stringifyAge = member.age.toString() // Object is possibly 'undefined'\n  })\n```\n\n## Non-Null Assertion Operator\n\nA new `!` post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. For example:\n\n```ts\n// Compiled with --strictNullChecks\nfunction validateEntity(e?: Entity) {\n    // Throw exception if e is null or invalid entity\n}\n\nfunction processEntity(e?: Entity) {\n    validateEntity(e);\n    let a = e.name;  // TS ERROR: e may be null.\n    let b = e!.name;  // OKAY. We are asserting that e is non-null.\n}\n```\n\n> Note that it is just an assertion, and just like type assertions *you are responsible* for making sure the value is not null. A non-null assertion is essentially you telling the compiler \"I know it's not null so let me use it as though it's not null\".\n\n### Definite Assignment Assertion Operator\n\nTypeScript will also complain about properties in classes not being initialized e.g.:\n\n```ts\nclass C {\n  foo: number; // OKAY as assigned in constructor\n  bar: string = \"hello\"; // OKAY as has property initializer\n  baz: boolean; // TS ERROR: Property 'baz' has no initializer and is not assigned directly in the constructor.\n  constructor() {\n    this.foo = 42;\n  }\n}\n```\n\nYou can use the definite assignment assertion postfixed to the property name to tell TypeScript that you are initializing it somewhere other than the constructor e.g.\n\n```ts\nclass C {\n  foo!: number;\n  // ^\n  // Notice this exclamation point!\n  // This is the \"definite assignment assertion\" modifier.\n  \n  constructor() {\n    this.initialize();\n  }\n  initialize() {\n    this.foo = 0;\n  }\n}\n```\n\nYou can also use this assertion with simple variable declarations e.g.:\n\n```ts\nlet a: number[]; // No assertion\nlet b!: number[]; // Assert\n\ninitialize();\n\na.push(4); // TS ERROR: variable used before assignment\nb.push(4); // OKAY: because of the assertion\n\nfunction initialize() {\n  a = [0, 1, 2, 3];\n  b = [0, 1, 2, 3];\n}\n```\n\n> Like all assertions, you are telling the compiler to trust you. The compiler will not complain even if the code doesn't actually always assign the property.\n"
  },
  {
    "path": "docs/project/compilation-context.md",
    "content": "## Compilation Context\nThe compilation context is basically just a fancy term for grouping of the files that TypeScript will parse and analyze to determine what is valid and what isn't. Along with the information about which files, the compilation context contains information about *which compiler options* are in use. A great way to define this logical grouping (we also like to use the term *project*) is using a `tsconfig.json` file.\n"
  },
  {
    "path": "docs/project/declarationspaces.md",
    "content": "## Declaration Spaces\n\nThere are two declaration spaces in TypeScript: the *variable* declaration space and the *type* declaration space. These concepts are explored below.\n\n### Type Declaration Space\nThe type declaration space contains stuff that can be used as a type annotation. E.g. the following are a few type declarations:\n\n```ts\nclass Foo {};\ninterface Bar {};\ntype Bas = {};\n```\nThis means that you can use `Foo`, `Bar`, `Bas`, etc. as a type annotation. E.g.:\n\n```ts\nvar foo: Foo;\nvar bar: Bar;\nvar bas: Bas;\n```\n\nNotice that even though you have `interface Bar`, *you can't use it as a variable* because it doesn't contribute to the *variable declaration space*. This is shown below:\n\n```ts\ninterface Bar {};\nvar bar = Bar; // ERROR: \"cannot find name 'Bar'\"\n```\n\nThe reason why it says `cannot find name` is because the name `Bar` *is not defined* in the *variable* declaration space. That brings us to the next topic \"Variable Declaration Space\".\n\n### Variable Declaration Space\nThe variable declaration space contains stuff that you can use as a variable. We saw that having `class Foo` contributes a type `Foo` to the *type* declaration space. Guess what? It also contributes a *variable* `Foo` to the *variable* declaration space as shown below:\n\n```ts\nclass Foo {};\nvar someVar = Foo;\nvar someOtherVar = 123;\n```\nThis is great as sometimes you want to pass classes around as variables. Remember that:\n\n* we couldn't use something like an `interface` that is *only* in the *type* declaration space as a variable.\n\nSimilarly something that you declare with `var`, is *only* in the *variable* declaration space and cannot be used as a type annotation:\n\n```ts\nvar foo = 123;\nvar bar: foo; // ERROR: \"cannot find name 'foo'\"\n```\nThe reason why it says `cannot find name` is because the name `foo` *is not defined* in the *type* declaration space.\n"
  },
  {
    "path": "docs/project/dynamic-import-expressions.md",
    "content": "## Dynamic import expressions \n\n**Dynamic import expressions** are a new feature and part of **ECMAScript** that allows users to asynchronously request a module at any arbitrary point in your program.\n**TC39** JavaScript committee has it’s own proposal which is in stage 3, and it’s called [import() proposal for JavaScript](https://github.com/tc39/proposal-dynamic-import).\n\nAlternatively, **webpack** bundler has a feature called [**Code Splitting**](https://webpack.js.org/guides/code-splitting/) which allows you to split your bundle into chunks which can be downloaded asynchronously at a later time. For instance, this allows to serve a minimal bootstrap bundle first and to asynchronously load additional features later.\n\nIt’s natural to think (if we are using webpack in our dev workflow) that [TypeScript 2.4 dynamic import expressions](https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#dynamic-import-expressions) will **automatically produce** bundle chunks and automatically code-split your JS final bundle. BUT, that is not as easy as it seems, because it depends on the **tsconfig.json configuration** we are working with.\n\nThe thing is that webpack code splitting supports two similar techniques to achieve this goal: using **import()** (preferred, ECMAScript proposal) and **require.ensure()** (legacy, webpack specific). And what that means is the expected TypeScript output is **leave the import() statement as it is** instead of transpile it to anything else.\n\nLet’s see an example to figure out how to configure webpack + TypeScript 2.4.\n\nIn the following code I want to **lazy load the library _moment_** but I am interested in code splitting as well, which means, having the moment library in a separate chunk of JS (JavaScript file) that will be loaded only when required.\n\n```ts\nimport(/* webpackChunkName: \"momentjs\" */ \"moment\")\n  .then((moment) => {\n      // lazyModule has all of the proper types, autocomplete works,\n      // type checking works, code references work \\o/\n      const time = moment().format();\n      console.log(\"TypeScript >= 2.4.0 Dynamic Import Expression:\");\n      console.log(time);\n  })\n  .catch((err) => {\n      console.log(\"Failed to load moment\", err);\n  });\n```\n\nHere is the tsconfig.json:\n\n```json\n{\n    \"compilerOptions\": {\n        \"target\": \"es5\",                          \n        \"module\": \"esnext\",                     \n        \"lib\": [\n            \"dom\",\n            \"es5\",\n            \"scripthost\",\n            \"es2015.promise\"\n        ],                                        \n        \"jsx\": \"react\",                           \n        \"declaration\": false,                     \n        \"sourceMap\": true,                        \n        \"outDir\": \"./dist/js\",                    \n        \"strict\": true,                           \n        \"moduleResolution\": \"node\",               \n        \"typeRoots\": [\n            \"./node_modules/@types\"\n        ],                                        \n        \"types\": [\n            \"node\",\n            \"react\",\n            \"react-dom\"\n        ]                                       \n    }\n}\n```\n\n\n**Important notes**:\n\n- Using **\"module\": \"esnext\"** TypeScript produces the mimic import() statement to be input for Webpack Code Splitting.\n- For further information read this article: [Dynamic Import Expressions and webpack 2 Code Splitting integration with TypeScript 2.4](https://blog.josequinto.com/2017/06/29/dynamic-import-expressions-and-webpack-code-splitting-integration-with-typescript-2-4/).\n\n\nYou can see full example [here][dynamicimportcode].\n\n[dynamicimportcode]:https://cdn.rawgit.com/basarat/typescript-book/705e4496/code/dynamic-import-expressions/dynamicImportExpression.js\n"
  },
  {
    "path": "docs/project/external-modules.md",
    "content": "## External modules\nThere is a lot of power and usability packed into the TypeScript external module pattern. Here we discuss its power and some patterns needed to reflect real world usages.\n\n### Clarification: commonjs, amd, es modules, others\n\nFirst up we need to clarify the (awful) inconsistency of the module systems out there. I'll just give you my *current* recommendation and remove the noise i.e. not show you all the *other* ways things can work.\n\nFrom the *same TypeScript* you can generate different *JavaScript* depending upon the `module` option. Here are things you can ignore (I am not interested in explaining dead tech):\n\n* AMD: Do not use. Was browser only.\n* SystemJS: Was a good experiment. Superseded by ES modules.\n* ES Modules: Not ready yet.\n\nNow these are just the options for *generating the JavaScript*. Instead of these options use `module:commonjs`\n\nHow you *write* TypeScript modules is also a bit of a mess. Again here is how not to do it *today*:\n\n* `import foo = require('foo')`. i.e. `import/require`. Use ES module syntax instead.\n\nCool, with that out of the way, lets look at the ES module syntax.\n\n> Summary: Use `module:commonjs` and use the ES module syntax to import / export / author modules.\n\n### ES Module syntax\n\n* Exporting a variable (or type) is as easy as prefixing the keyword `export` e.g.\n\n```js\n// file `foo.ts`\nexport let someVar = 123;\nexport type SomeType = {\n  foo: string;\n};\n```\n\n* Exporting a variable or type in a dedicated `export` statement e.g.\n\n```js\n// file `foo.ts`\nlet someVar = 123;\ntype SomeType = {\n  foo: string;\n};\nexport {\n  someVar,\n  SomeType\n};\n```\n* Exporting a variable or type in a dedicated `export` statement *with renaming* e.g.\n\n```js\n// file `foo.ts`\nlet someVar = 123;\nexport { someVar as aDifferentName };\n```\n\n* Import a variable or a type using `import` e.g.\n\n```js\n// file `bar.ts`\nimport { someVar, SomeType } from './foo';\n```\n\n* Import a variable or a type using `import` *with renaming* e.g.\n\n```js\n// file `bar.ts`\nimport { someVar as aDifferentName } from './foo';\n```\n\n* Import everything from a module into a name with `import * as` e.g.\n\n```js\n// file `bar.ts`\nimport * as foo from './foo';\n// you can use `foo.someVar` and `foo.SomeType` and anything else that foo might export.\n```\n\n* Import a file *only* for its side effect with a single import statement:\n\n```js\nimport 'core-js'; // a common polyfill library\n```\n\n* Re-Exporting all the items from another module\n\n```js\nexport * from './foo';\n```\n\n* Re-Exporting only some items from another module\n\n```js\nexport { someVar } from './foo';\n```\n\n* Re-Exporting only some items from another module *with renaming*\n\n```js\nexport { someVar as aDifferentName } from './foo';\n```\n\n### Default exports/imports\nAs you will learn later, I am not a fan of default exports. Nevertheless here is syntax for export and using default exports\n\n* Export using `export default`\n  * before a variable (no `let / const / var` needed)\n  * before a function\n  * before a class\n\n```js\n// some var\nexport default someVar = 123;\n// OR Some function\nexport default function someFunction() { }\n// OR Some class\nexport default class SomeClass { }\n```\n\n* Import using the `import someName from \"someModule\"` syntax (you can name the import whatever you want) e.g.\n\n```js\nimport someLocalNameForThisFile from \"../foo\";\n```\n\n### Module paths\n\n> I am just going to assume `moduleResolution: \"Node\"`. This is the option you should have in your TypeScript config. This setting is implied automatically by `module:commonjs`.\n\nThere are two distinct kinds of modules. The distinction is driven by the path section of the import statement (e.g. `import foo from 'THIS IS THE PATH SECTION'`).\n\n* Relative path modules (where path starts with `.` e.g. `./someFile` or `../../someFolder/someFile` etc.)\n* Other dynamic lookup modules (e.g. `'core-js'` or `'typestyle'` or `'react'` or even `'react/core'` etc.)\n\nThe main difference is *how the module is resolved on the file system*.\n\n> I will use a conceptual term *place* that I will explain after mentioning the lookup pattern.\n\n#### Relative path modules\nEasy, just follow the relative path :) e.g.\n\n* if file `bar.ts` does `import * as foo from './foo';` then place `foo` must exist in the same folder.\n* if file `bar.ts` does `import * as foo from '../foo';` then place `foo` must exist in a folder up.\n* if file `bar.ts` does `import * as foo from '../someFolder/foo';` then one folder up, there must be a folder `someFolder` with a place `foo`\n\nOr any other relative path you can think of :)\n\n#### Dynamic lookup\n\nWhen the import path is *not* relative, lookup is driven by [*node style resolution*](https://nodejs.org/api/modules.html#modules_all_together). Here I only give a simple example:\n\n* You have `import * as foo from 'foo'`, the following are the places that are checked *in order*\n  * `./node_modules/foo`\n  * `../node_modules/foo`\n  * `../../node_modules/foo`\n  * Till root of file system\n\n* You have `import * as foo from 'something/foo'`, the following are the places that are checked *in order*\n  * `./node_modules/something/foo`\n  * `../node_modules/something/foo`\n  * `../../node_modules/something/foo`\n  * Till root of file system\n\n\n### What is *place*\nWhen I say *places that are checked* I mean that the following things are checked in that place. e.g. for a place `foo`:\n\n* If the place is a file, e.g. `foo.ts`, hurray!\n* else if the place is a folder and there is a file `foo/index.ts`, hurray!\n* else if the place is a folder and there is a `foo/package.json` and a file specified in the `types` key in the package.json that exists, then hurray!\n* else if the place is a folder and there is a `package.json` and a file specified in the `main` key in the package.json that exists, then hurray!\n\nBy file I actually mean `.ts` / `.d.ts` and `.js`.\n\nAnd that's it. You are now module lookup experts (not a small feat!).\n\n### Overturning dynamic lookup *just for types*\nYou can declare a module *globally* for your project by using `declare module 'somePath'` and then imports will resolve *magically* to that path\n\ne.g.\n```ts\n// global.d.ts\ndeclare module 'foo' {\n  // Some variable declarations\n  export var bar: number; /*sample*/\n}\n```\n\nand then:\n```ts\n// anyOtherTsFileInYourProject.ts\nimport * as foo from 'foo';\n// TypeScript assumes (without doing any lookup) that\n// foo is {bar:number}\n\n```\n\n### `import/require` for importing type only\nThe following statement:\n\n```ts\nimport foo = require('foo');\n```\n\nactually does *two* things:\n\n* Imports the type information of the foo module.\n* Specifies a runtime dependency on the foo module.\n\nYou can pick and choose so that only *the type information* is loaded and no runtime dependency occurs. Before continuing you might want to recap the [*declaration spaces*](../project/declarationspaces.md) section of the book.\n\nIf you do not use the imported name in the variable declaration space then the import is completely removed from the generated JavaScript. This is best explained with examples. Once you understand this we will present you with use cases.\n\n#### Example 1\n```ts\nimport foo = require('foo');\n```\nwill generate the JavaScript:\n\n```js\n\n```\nThat's right. An *empty* file as foo is not used.\n\n#### Example 2\n```ts\nimport foo = require('foo');\nvar bar: foo;\n```\nwill generate the JavaScript:\n```js\nvar bar;\n```\nThis is because `foo` (or any of its properties e.g. `foo.bas`) is never used as a variable.\n\n#### Example 3\n```ts\nimport foo = require('foo');\nvar bar = foo;\n```\nwill generate the JavaScript (assuming commonjs):\n```js\nvar foo = require('foo');\nvar bar = foo;\n```\nThis is because `foo` is used as a variable.\n\n\n### Use case: Lazy loading\nType inference needs to be done *upfront*. This means that if you want to use some type from a file `foo` in a file `bar` you will have to do:\n\n```ts\nimport foo = require('foo');\nvar bar: foo.SomeType;\n```\nHowever, you might want to only load the file `foo` at runtime under certain conditions. For such cases you should use the `import`ed name only in *type annotations* and **not** as a *variable*. This removes any *upfront* runtime dependency code being injected by TypeScript. Then *manually import* the actual module using code that is specific to your module loader.\n\nAs an example, consider the following `commonjs` based code where we only load a module `'foo'` on a certain function call:\n\n```ts\nimport foo = require('foo');\n\nexport function loadFoo() {\n    // This is lazy loading `foo` and using the original module *only* as a type annotation\n    var _foo: typeof foo = require('foo');\n    // Now use `_foo` as a variable instead of `foo`.\n}\n```\n\nA similar sample in `amd` (using requirejs) would be:\n```ts\nimport foo = require('foo');\n\nexport function loadFoo() {\n    // This is lazy loading `foo` and using the original module *only* as a type annotation\n    require(['foo'], (_foo: typeof foo) => {\n        // Now use `_foo` as a variable instead of `foo`.\n    });\n}\n```\n\nThis pattern is commonly used:\n* in web apps where you load certain JavaScript on particular routes,\n* in node applications where you only load certain modules if needed to speed up application bootup.\n\n### Use case: Breaking Circular dependencies\n\nSimilar to the lazy loading use case certain module loaders (commonjs/node and amd/requirejs) don't work well with circular dependencies. In such cases it is useful to have *lazy loading* code in one direction and loading the modules upfront in the other direction.\n\n### Use case: Ensure Import\n\nSometimes you want to load a file just for the side effect (e.g. the module might register itself with some library like [CodeMirror addons](https://codemirror.net/doc/manual.html#addons) etc.). However, if you just do a `import/require` the transpiled JavaScript will not contain a dependency on the module and your module loader (e.g. webpack) might completely ignore the import. In such cases you can use a `ensureImport` variable to ensure that the compiled JavaScript takes a dependency on the module e.g.:\n\n```ts\nimport foo = require('./foo');\nimport bar = require('./bar');\nimport bas = require('./bas');\nconst ensureImport: any =\n    foo\n    && bar\n    && bas;\n```\n"
  },
  {
    "path": "docs/project/files.md",
    "content": "## Which files?\n\nUse `include` and `exclude` to specify files / folders / globs. E.g.:\n\n\n```json\n{\n    \"include\":[\n        \"./folder\"\n    ],\n    \"exclude\":[\n        \"./folder/**/*.spec.ts\",\n        \"./folder/someSubFolder\"\n    ]\n}\n```\n\n### Globs\n\n* For globs : `**/*` (e.g. sample usage `somefolder/**/*`) means all folder and any files (the extensions `.ts`/`.tsx` will be assumed and if `allowJs:true` so will `.js`/`.jsx`)\n\n### `files` option\nAlternatively, you can use `files` to be explicit: \n\n```json\n{\n    \"files\":[\n        \"./some/file.ts\"\n    ]\n}\n```\n\nBut it is not recommended as you have to keep updating it. Instead use `include` to just add the containing folder. \n"
  },
  {
    "path": "docs/project/globals.md",
    "content": "# global.d.ts\n\nWe discussed *global* vs. *file* modules when covering [projects](./modules.md) and recommended using file based modules and not polluting the global namespace.\n\nNevertheless, if you have beginner TypeScript developers you can give them a `global.d.ts` file to put interfaces / types in the global namespace to make it easy to have some *types* just *magically* available for consumption in *all* your TypeScript code.\n\nAnother use case for a `global.d.ts` file is to declare compile-time constants that are being injected into the source code by Webpack via the standard [DefinePlugin](https://webpack.js.org/plugins/define-plugin/) plugin.\n\n```ts\ndeclare const BUILD_MODE_PRODUCTION: boolean; // can be used for conditional compiling\ndeclare const BUILD_VERSION: string;\n```\n\n> For any code that is going to generate *JavaScript* we highly recommend using *file modules*, and only use `global.d.ts` to declare compile-time constants and/or to extend standard type declarations declared in `lib.d.ts`.\n\n* Bonus: The `global.d.ts` file is also good for quick `declare module \"some-library-you-dont-care-to-get-defs-for\";` when doing JS to TS migrations.\n"
  },
  {
    "path": "docs/project/module-resolution.md",
    "content": "# TypeScript Module Resolution\n\nTypeScript's module resolution tries to model and support the real world modules systems / loaders there (commonjs/nodejs, amd/requirejs, ES6/systemjs etc.). The most simplest lookup is relative file path lookup. After that things become a bit complex *because of the nature of magical module loading done by various module loaders*.\n\n## File Extensions\n\nYou import modules like `foo` or `./foo`. For any file path lookup TypeScript automatically checks for a `.ts` or `.d.ts` or `.tsx` or `.js` (optionally) or `.jsx` (optionally) file in the right order depending upon context. You should **not** provide a file extension with the module name (no `foo.ts`, just `foo`).\n\n## Relative File Module\n\nAn import with a relative path e.g.:\n\n```ts\nimport foo = require('./foo');\n```\n\nTells the TypeScript compiler to look for a TypeScript file at the relative location e.g. `./foo.ts` with respect to the current file. There is no further magic to this kind of import. Of course it can be a longer path e.g. `./foo/bar/bas` or `../../../foo/bar/bas` just like any other *relative paths* you are used to on disk.\n\n## Named Module\n\nThe following statement:\n\n```ts\nimport foo = require('foo');\n```\n\nTells the TypeScript compiler to look for an external module in the following order:\n\n* A named [module declaration](#module-declaration) from a file already in the compilation context.\n* If still not resolved and you are compiling with `--module commonjs`  or have set `--moduleResolution node` then its looked up using the [*node modules*](#node-modules) resolution algorithm.\n* If still not resolved and you provided `baseUrl` (and optionally `paths`) then the [*path substitutions*](#path-substitutions) resolution algorithm kicks in.\n\nNote that `\"foo\"` can be a longer path string e.g. `\"foo/bar/bas\"`. The key here is that *it does not start with `./` or `../`*.\n\n## Module Declaration\n\nA module declaration looks like:\n\n```ts\ndeclare module \"foo\" {\n\n    /// Some variable declarations\n\n    export var bar:number; /*sample*/\n}\n```\n\nThis makes the module `\"foo\"`, *importable*.\n\n## Node Modules\nThe node module resolution is actually pretty much the same one used by Node.js / NPM ([official nodejs docs](https://nodejs.org/api/modules.html#modules_all_together)). Here is a simple mental model I have:\n\n* module `foo/bar` will resolve to some file : `node_modules/foo` (the module) + `foo/bar`\n\n## Path Substitutions\n\nTODO.\n\n[//Comment1]:https://github.com/Microsoft/TypeScript/issues/2338\n[//Comment2]:https://github.com/Microsoft/TypeScript/issues/5039\n[//Comment3ExampleRedirectOfPackageJson]:https://github.com/Microsoft/TypeScript/issues/8528#issuecomment-219172026\n[//Coment4ModuleResolutionInHandbook]:https://github.com/Microsoft/TypeScript-Handbook/blob/release-2.0/pages/Module%20Resolution.md#base-url\n"
  },
  {
    "path": "docs/project/modules.md",
    "content": "## Modules\n\n### Global Module\n\nBy default when you start typing code in a new TypeScript file your code is in a *global* namespace. As a demo consider a file `foo.ts`:\n\n```ts\nvar foo = 123;\n```\n\nIf you now create a *new* file `bar.ts` in the same project, you will be *allowed* by the TypeScript type system to use the variable `foo` as if it was available globally:\n\n```ts\nvar bar = foo; // allowed\n```\nNeedless to say having a global namespace is dangerous as it opens your code up for naming conflicts. We recommend using file modules which are presented next.\n\n### File Module\nAlso called *external modules*. If you have an `import` or an `export` at the root level of a TypeScript file then it creates a *local* scope within that file. So if we were to change the previous `foo.ts` to the following (note the `export` usage):\n\n```ts\nexport var foo = 123;\n```\n\nWe will no longer have `foo` in the global namespace. This can be demonstrated by creating a new file `bar.ts` as follows:\n\n```ts\nvar bar = foo; // ERROR: \"cannot find name 'foo'\"\n```\n\nIf you want to use stuff from `foo.ts` in `bar.ts` *you need to explicitly import it*. This is shown in an updated `bar.ts` below:\n\n```ts\nimport { foo } from \"./foo\";\nvar bar = foo; // allowed\n```\nUsing an `import` in `bar.ts` not only allows you to bring in stuff from other files, but also marks the file `bar.ts` as a *module* and therefore, declarations in `bar.ts` don't pollute the global namespace either.\n\nWhat JavaScript is generated from a given TypeScript file that uses external modules is driven by the compiler flag called `module`.\n"
  },
  {
    "path": "docs/project/namespaces.md",
    "content": "## Namespaces\nNamespaces provide you with a convenient syntax around a common pattern used in JavaScript:\n\n```ts\n(function(something) {\n\n    something.foo = 123;\n\n})(something || (something = {}))\n```\n\nBasically `something || (something = {})` allows an anonymous function `function(something) {}` to *add stuff to an existing object* (the `something ||` portion) or *start a new object then add stuff to that object* (the `|| (something = {})` portion). This means that you can have two such blocks split by some execution boundary:\n\n```ts\n(function(something) {\n\n    something.foo = 123;\n\n})(something || (something = {}))\n\nconsole.log(something); // {foo:123}\n\n(function(something) {\n\n    something.bar = 456;\n\n})(something || (something = {}))\n\nconsole.log(something); // {foo:123, bar:456}\n\n```\n\nThis is commonly used in  the JavaScript land for making sure that stuff doesn't leak into the global namespace. With file based modules you don't need to worry about this, but the pattern is still useful for *logical grouping* of a bunch of functions. Therefore TypeScript provides the `namespace` keyword to group these e.g.:\n\n```ts\nnamespace Utility {\n    export function log(msg) {\n        console.log(msg);\n    }\n    export function error(msg) {\n        console.error(msg);\n    }\n}\n\n// usage\nUtility.log('Call me');\nUtility.error('maybe!');\n```\n\nThe `namespace` keyword generates the same JavaScript that we saw earlier:\n\n```ts\n(function (Utility) {\n\n// Add stuff to Utility\n\n})(Utility || (Utility = {}));\n```\n\nOne thing to note is that namespaces can be nested so you can do stuff like `namespace Utility.Messaging` to nest a `Messaging` namespace under `Utility`.\n\nFor most projects we recommend using external modules and using `namespace` for quick demos and porting old JavaScript code.\n"
  },
  {
    "path": "docs/project/project.md",
    "content": "# Project\n\nTo create a successful project using TypeScript you need to understand the various project organization language features available. In this section we will cover \"compilation context\", declaration spaces and modules.\n"
  },
  {
    "path": "docs/project/tsconfig.md",
    "content": "### Basic\nIt is extremely easy to get started with tsconfig.json as the basic file you need is:\n```json\n{}\n```\ni.e. an empty JSON file at the *root* of your project. This way TypeScript will include *all* the `.ts` files in this directory (and sub directories) as a part of the compilation context. It will also select a few sane default compiler options.\n\n### compilerOptions\nYou can customize the compiler options using `compilerOptions`:\n\n```json\n{\n  \"compilerOptions\": {\n\n    /* Basic Options */                       \n    \"target\": \"es5\",                       /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */\n    \"module\": \"commonjs\",                  /* Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'. */\n    \"lib\": [],                             /* Specify library files to be included in the compilation:  */\n    \"allowJs\": true,                       /* Allow JavaScript files to be compiled. */\n    \"checkJs\": true,                       /* Report errors in .js files. */\n    \"jsx\": \"preserve\",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */\n    \"declaration\": true,                   /* Generates corresponding '.d.ts' file. */\n    \"sourceMap\": true,                     /* Generates corresponding '.map' file. */\n    \"outFile\": \"./\",                       /* Concatenate and emit output to single file. */\n    \"outDir\": \"./\",                        /* Redirect output structure to the directory. */\n    \"rootDir\": \"./\",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */\n    \"removeComments\": true,                /* Do not emit comments to output. */\n    \"noEmit\": true,                        /* Do not emit outputs. */\n    \"importHelpers\": true,                 /* Import emit helpers from 'tslib'. */\n    \"downlevelIteration\": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */\n    \"isolatedModules\": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */\n                                              \n    /* Strict Type-Checking Options */        \n    \"strict\": true,                        /* Enable all strict type-checking options. */\n    \"noImplicitAny\": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */\n    \"strictNullChecks\": true,              /* Enable strict null checks. */\n    \"noImplicitThis\": true,                /* Raise error on 'this' expressions with an implied 'any' type. */\n    \"alwaysStrict\": true,                  /* Parse in strict mode and emit \"use strict\" for each source file. */\n                                              \n    /* Additional Checks */                   \n    \"noUnusedLocals\": true,                /* Report errors on unused locals. */\n    \"noUnusedParameters\": true,            /* Report errors on unused parameters. */\n    \"noImplicitReturns\": true,             /* Report error when not all code paths in function return a value. */\n    \"noFallthroughCasesInSwitch\": true,    /* Report errors for fallthrough cases in switch statement. */\n                                              \n    /* Module Resolution Options */           \n    \"moduleResolution\": \"node\",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */\n    \"baseUrl\": \"./\",                       /* Base directory to resolve non-absolute module names. */\n    \"paths\": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */\n    \"rootDirs\": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */\n    \"typeRoots\": [],                       /* List of folders to include type definitions from. */\n    \"types\": [],                           /* Type declaration files to be included in compilation. */\n    \"allowSyntheticDefaultImports\": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */\n                                              \n    /* Source Map Options */                  \n    \"sourceRoot\": \"./\",                    /* Specify the location where debugger should locate TypeScript files instead of source locations. */\n    \"mapRoot\": \"./\",                       /* Specify the location where debugger should locate map files instead of generated locations. */\n    \"inlineSourceMap\": true,               /* Emit a single file with source maps instead of having a separate file. */\n    \"inlineSources\": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */\n                                              \n    /* Experimental Options */                \n    \"experimentalDecorators\": true,        /* Enables experimental support for ES7 decorators. */\n    \"emitDecoratorMetadata\": true          /* Enables experimental support for emitting type metadata for decorators. */\n  }\n}\n```\n\nThese (and more) compiler options will be discussed later.\n\n### TypeScript compiler\nGood IDEs come with built in support for on the fly `ts` to `js` compilation. However, if you want to run the TypeScript compiler manually from the command line when using `tsconfig.json`, you can do it in a few ways:\n* Just run `tsc` and it will look for `tsconfig.json` in the current as well as all parent folders till it finds it.\n* Run `tsc -p ./path-to-project-directory`. Of course the path can be absolute or relative to the current directory.\n\nYou can even start the TypeScript compiler in *watch* mode using `tsc -w` and it will watch your TypeScript project files for changes.\n"
  },
  {
    "path": "docs/promise.md",
    "content": "## Promise\n\nThe `Promise` class is something that exists in many modern JavaScript engines and can be easily [polyfilled][polyfill]. The main motivation for promises is to bring synchronous style error handling to Async / Callback style code.\n\n### Callback style code\n\nIn order to fully appreciate promises let's present a simple sample that proves the difficulty of creating reliable Async code with just callbacks. Consider the simple case of authoring an async version of loading JSON from a file. A synchronous version of this can be quite simple:\n\n```ts\nimport fs = require('fs');\n\nfunction loadJSONSync(filename: string) {\n    return JSON.parse(fs.readFileSync(filename));\n}\n\n// good json file\nconsole.log(loadJSONSync('good.json'));\n\n// non-existent file, so fs.readFileSync fails\ntry {\n    console.log(loadJSONSync('absent.json'));\n}\ncatch (err) {\n    console.log('absent.json error', err.message);\n}\n\n// invalid json file i.e. the file exists but contains invalid JSON so JSON.parse fails\ntry {\n    console.log(loadJSONSync('invalid.json'));\n}\ncatch (err) {\n    console.log('invalid.json error', err.message);\n}\n```\n\nThere are three behaviors of this simple `loadJSONSync` function, a valid return value, a file system error or a JSON.parse error. We handle the errors with a simple try/catch as you are used to when doing synchronous programming in other languages. Now let's make a good async version of such a function. A decent initial attempt with trivial error checking logic would be as follows:\n\n```ts\nimport fs = require('fs');\n\n// A decent initial attempt .... but not correct. We explain the reasons below\nfunction loadJSON(filename: string, cb: (error: Error, data: any) => void) {\n    fs.readFile(filename, function (err, data) {\n        if (err) cb(err);\n        else cb(null, JSON.parse(data));\n    });\n}\n```\n\nSimple enough, it takes a callback, passes any file system errors to the callback. If no file system errors, it returns the `JSON.parse` result. A few points to keep in mind when working with async functions based on callbacks are:\n\n1. Never call the callback twice.\n1. Never throw an error.\n\nHowever, this simple function fails to accommodate for point two. In fact, `JSON.parse` throws an error if it is passed bad JSON and the callback never gets called and the application crashes. This is demonstrated in the below example:\n\n```ts\nimport fs = require('fs');\n\n// A decent initial attempt .... but not correct\nfunction loadJSON(filename: string, cb: (error: Error, data: any) => void) {\n    fs.readFile(filename, function (err, data) {\n        if (err) cb(err);\n        else cb(null, JSON.parse(data));\n    });\n}\n\n// load invalid json\nloadJSON('invalid.json', function (err, data) {\n    // This code never executes\n    if (err) console.log('bad.json error', err.message);\n    else console.log(data);\n});\n```\n\nA naive attempt at fixing this would be to wrap the `JSON.parse` in a try catch as shown in the below example:\n\n```ts\nimport fs = require('fs');\n\n// A better attempt ... but still not correct\nfunction loadJSON(filename: string, cb: (error: Error) => void) {\n    fs.readFile(filename, function (err, data) {\n        if (err) {\n            cb(err);\n        }\n        else {\n            try {\n                cb(null, JSON.parse(data));\n            }\n            catch (err) {\n                cb(err);\n            }\n        }\n    });\n}\n\n// load invalid json\nloadJSON('invalid.json', function (err, data) {\n    if (err) console.log('bad.json error', err.message);\n    else console.log(data);\n});\n```\n\nHowever, there is a subtle bug in this code. If the callback (`cb`), and not `JSON.parse`, throws an error, since we wrapped it in a `try`/`catch`, the `catch` executes and we call the callback again i.e. the callback gets called twice! This is demonstrated in the example below:\n\n```ts\nimport fs = require('fs');\n\nfunction loadJSON(filename: string, cb: (error: Error) => void) {\n    fs.readFile(filename, function (err, data) {\n        if (err) {\n            cb(err);\n        }\n        else {\n            try {\n                cb(null, JSON.parse(data));\n            }\n            catch (err) {\n                cb(err);\n            }\n        }\n    });\n}\n\n// a good file but a bad callback ... gets called again!\nloadJSON('good.json', function (err, data) {\n    console.log('our callback called');\n\n    if (err) console.log('Error:', err.message);\n    else {\n        // let's simulate an error by trying to access a property on an undefined variable\n        var foo;\n        // The following code throws `Error: Cannot read property 'bar' of undefined`\n        console.log(foo.bar);\n    }\n});\n```\n\n```bash\n$ node asyncbadcatchdemo.js\nour callback called\nour callback called\nError: Cannot read property 'bar' of undefined\n```\n\nThis is because our `loadJSON` function wrongfully wrapped the callback in a `try` block. There is a simple lesson to remember here.\n\n> Simple lesson: Contain all your sync code in a try catch, except when you call the callback.\n\nFollowing this simple lesson, we have a fully functional async version of `loadJSON` as shown below:\n\n```ts\nimport fs = require('fs');\n\nfunction loadJSON(filename: string, cb: (error: Error) => void) {\n    fs.readFile(filename, function (err, data) {\n        if (err) return cb(err);\n        // Contain all your sync code in a try catch\n        try {\n            var parsed = JSON.parse(data);\n        }\n        catch (err) {\n            return cb(err);\n        }\n        // except when you call the callback\n        return cb(null, parsed);\n    });\n}\n```\nAdmittedly this is not hard to follow once you've done it a few times but nonetheless it’s a lot of boiler plate code to write simply for good error handling. Now let's look at a better way to tackle asynchronous JavaScript using promises.\n\n## Creating a Promise\n\nA promise can be either `pending` or `fulfilled` or `rejected`.\n\n![promise states and fates](https://raw.githubusercontent.com/basarat/typescript-book/master/images/promise%20states%20and%20fates.png)\n\nLet's look at creating a promise. It's a simple matter of calling `new` on `Promise` (the promise constructor). The promise constructor is passed `resolve` and `reject` functions for settling the promise state:\n\n```ts\nconst promise = new Promise((resolve, reject) => {\n    // the resolve / reject functions control the fate of the promise\n});\n```\n\n### Subscribing to the fate of the promise\n\nThe promise fate can be subscribed to using `.then` (if resolved) or `.catch` (if rejected).\n\n```ts\nconst promise = new Promise((resolve, reject) => {\n    resolve(123);\n});\npromise.then((res) => {\n    console.log('I get called:', res === 123); // I get called: true\n});\npromise.catch((err) => {\n    // This is never called\n});\n```\n\n```ts\nconst promise = new Promise((resolve, reject) => {\n    reject(new Error(\"Something awful happened\"));\n});\npromise.then((res) => {\n    // This is never called\n});\npromise.catch((err) => {\n    console.log('I get called:', err.message); // I get called: 'Something awful happened'\n});\n```\n\n> TIP: Promise Shortcuts\n* Quickly creating an already resolved promise: `Promise.resolve(result)`\n* Quickly creating an already rejected promise: `Promise.reject(error)`\n\n### Chain-ability of Promises\nThe chain-ability of promises **is the heart of the benefit that promises provide**. Once you have a promise, from that point on, you use the `then` function to create a chain of promises.\n\n* If you return a promise from any function in the chain, `.then` is only called once the value is resolved:\n\n```ts\nPromise.resolve(123)\n    .then((res) => {\n        console.log(res); // 123\n        return 456;\n    })\n    .then((res) => {\n        console.log(res); // 456\n        return Promise.resolve(123); // Notice that we are returning a Promise\n    })\n    .then((res) => {\n        console.log(res); // 123 : Notice that this `then` is called with the resolved value\n        return 123;\n    })\n```\n\n* You can aggregate the error handling of any preceding portion of the chain with a single `catch`:\n\n```ts\n// Create a rejected promise\nPromise.reject(new Error('something bad happened'))\n    .then((res) => {\n        console.log(res); // not called\n        return 456;\n    })\n    .then((res) => {\n        console.log(res); // not called\n        return 123;\n    })\n    .then((res) => {\n        console.log(res); // not called\n        return 123;\n    })\n    .catch((err) => {\n        console.log(err.message); // something bad happened\n    });\n```\n\n* The `catch` actually returns a new promise (effectively creating a new promise chain):\n\n```ts\n// Create a rejected promise\nPromise.reject(new Error('something bad happened'))\n    .then((res) => {\n        console.log(res); // not called\n        return 456;\n    })\n    .catch((err) => {\n        console.log(err.message); // something bad happened\n        return 123;\n    })\n    .then((res) => {\n        console.log(res); // 123\n    })\n```\n\n* Any synchronous errors thrown in a `then` (or `catch`) result in the returned promise to fail:\n\n```ts\nPromise.resolve(123)\n    .then((res) => {\n        throw new Error('something bad happened'); // throw a synchronous error\n        return 456;\n    })\n    .then((res) => {\n        console.log(res); // never called\n        return Promise.resolve(789);\n    })\n    .catch((err) => {\n        console.log(err.message); // something bad happened\n    })\n```\n\n* Only the relevant (nearest tailing) `catch` is called for a given error (as the catch starts a new promise chain).\n\n```ts\nPromise.resolve(123)\n    .then((res) => {\n        throw new Error('something bad happened'); // throw a synchronous error\n        return 456;\n    })\n    .catch((err) => {\n        console.log('first catch: ' + err.message); // something bad happened\n        return 123;\n    })\n    .then((res) => {\n        console.log(res); // 123\n        return Promise.resolve(789);\n    })\n    .catch((err) => {\n        console.log('second catch: ' + err.message); // never called\n    })\n```\n\n* A `catch` is only called in case of an error in the preceding chain:\n\n```ts\nPromise.resolve(123)\n    .then((res) => {\n        return 456;\n    })\n    .catch((err) => {\n        console.log(\"HERE\"); // never called\n    })\n```\n\nThe fact that:\n\n* errors jump to the tailing `catch` (and skip any middle `then` calls) and\n* synchronous errors also get caught by any tailing `catch`.\n\neffectively provides us with an async programming paradigm that allows better error handling than raw callbacks. More on this below.\n\n\n### TypeScript and promises\nThe great thing about TypeScript is that it understands the flow of values through a promise chain:\n\n```ts\nPromise.resolve(123)\n    .then((res) => {\n         // res is inferred to be of type `number`\n         return true;\n    })\n    .then((res) => {\n        // res is inferred to be of type `boolean`\n\n    });\n```\n\nOf course it also understands unwrapping any function calls that might return a promise:\n\n```ts\nfunction iReturnPromiseAfter1Second(): Promise<string> {\n    return new Promise((resolve) => {\n        setTimeout(() => resolve(\"Hello world!\"), 1000);\n    });\n}\n\nPromise.resolve(123)\n    .then((res) => {\n        // res is inferred to be of type `number`\n        return iReturnPromiseAfter1Second(); // We are returning `Promise<string>`\n    })\n    .then((res) => {\n        // res is inferred to be of type `string`\n        console.log(res); // Hello world!\n    });\n```\n\n\n### Converting a callback style function to return a promise\n\nJust wrap the function call in a promise and\n- `reject` if an error occurs,\n- `resolve` if it is all good.\n\nE.g. let's wrap `fs.readFile`:\n\n```ts\nimport fs = require('fs');\nfunction readFileAsync(filename: string): Promise<any> {\n    return new Promise((resolve,reject) => {\n        fs.readFile(filename,(err,result) => {\n            if (err) reject(err);\n            else resolve(result);\n        });\n    });\n}\n```\n\nThe most reliable way to do this is to hand write it and it doesn't have to be as verbose as the previous example e.g. converting `setTimeout` into a promisified `delay` function is super easy:\n\n```ts\nconst delay = (ms: number) => new Promise(res => setTimeout(res, ms));\n```\n\nNote that there is a handy dandy function in NodeJS that does this `node style function => promise returning function` magic for you:\n\n```ts\n/** Sample usage */\nimport fs from 'fs';\nimport util from 'util';\nconst readFile = util.promisify(fs.readFile);\n```\n\n> Webpack supports the `util` module out of the box and you can use it in the browser as well.\n\nIf you have a node callback style function as a *member* be sure to `bind` it as well to make sure it has the correct `this`: \n\n```ts\nconst dbGet = util.promisify(db.get).bind(db);\n```\n\n### Revisiting the JSON example\n\nNow let's revisit our `loadJSON` example and rewrite an async version that uses promises. All that we need to do is read the file contents as a promise, then parse them as JSON and we are done. This is illustrated in the below example:\n\n```ts\nfunction loadJSONAsync(filename: string): Promise<any> {\n    return readFileAsync(filename) // Use the function we just wrote\n                .then(function (res) {\n                    return JSON.parse(res);\n                });\n}\n```\n\nUsage (notice how similar it is to the original `sync` version introduced at the start of this section 🌹):\n```ts\n// good json file\nloadJSONAsync('good.json')\n    .then(function (val) { console.log(val); })\n    .catch(function (err) {\n        console.log('good.json error', err.message); // never called\n    })\n\n// non-existent json file\n    .then(function () {\n        return loadJSONAsync('absent.json');\n    })\n    .then(function (val) { console.log(val); }) // never called\n    .catch(function (err) {\n        console.log('absent.json error', err.message);\n    })\n\n// invalid json file\n    .then(function () {\n        return loadJSONAsync('invalid.json');\n    })\n    .then(function (val) { console.log(val); }) // never called\n    .catch(function (err) {\n        console.log('bad.json error', err.message);\n    });\n```\n\nThe reason why this function was simpler is because the \"`loadFile`(async) + `JSON.parse` (sync) => `catch`\" consolidation was done by the promise chain. Also the callback was not called by *us* but called by the promise chain so we didn't have the chance of making the mistake of wrapping it in a `try/catch`.\n\n### Parallel control flow\nWe have seen how trivial doing a serial sequence of async tasks is with promises. It is simply a matter of chaining `then` calls.\n\nHowever, you might potentially want to run a series of async tasks and then do something with the results of all of these tasks. `Promise` provides a static `Promise.all` function that you can use to wait for `n` number of promises to complete. You provide it with an array of `n` promises and it gives you an array of `n` resolved values. Below we show Chaining as well as Parallel:\n\n```ts\n// an async function to simulate loading an item from some server\nfunction loadItem(id: number): Promise<{ id: number }> {\n    return new Promise((resolve) => {\n        console.log('loading item', id);\n        setTimeout(() => { // simulate a server delay\n            resolve({ id: id });\n        }, 1000);\n    });\n}\n\n// Chained / Sequential\nlet item1, item2;\nloadItem(1)\n    .then((res) => {\n        item1 = res;\n        return loadItem(2);\n    })\n    .then((res) => {\n        item2 = res;\n        console.log('done');\n    }); // overall time will be around 2s\n\n// Concurrent / Parallel\nPromise.all([loadItem(1), loadItem(2)])\n    .then((res) => {\n        [item1, item2] = res;\n        console.log('done');\n    }); // overall time will be around 1s\n```\n\nSometimes, you want to run a series of async tasks, but you get all you need as long as any one of these tasks is settled. `Promise` provides a static `Promise.race` function for this scenario:\n\n```ts\nvar task1 = new Promise(function(resolve, reject) {\n    setTimeout(resolve, 1000, 'one');\n});\nvar task2 = new Promise(function(resolve, reject) {\n    setTimeout(resolve, 2000, 'two');\n});\n\nPromise.race([task1, task2]).then(function(value) {\n  console.log(value); // \"one\"\n  // Both resolve, but task1 resolves faster\n});\n```\n\n[polyfill]:https://github.com/stefanpenner/es6-promise\n"
  },
  {
    "path": "docs/quick/browser.md",
    "content": "# TypeScript in the browser\n\n[![DesignTSX](https://raw.githubusercontent.com/basarat/typescript-book/master/images/designtsx-banner.png)](https://designtsx.com)\n\nIf you are using TypeScript to create a web application here are my recommendations to get a quick TypeScript + React (my UI framework of choice) project setup.\n\n## General Machine Setup\n\n* Install [Node.js](https://nodejs.org/en/download/)\n* Install [Git](https://git-scm.com/downloads)\n\n## Project Setup Quick\nUse [https://github.com/basarat/react-typescript](https://github.com/basarat/react-typescript) as a base. \n\n```\ngit clone https://github.com/basarat/react-typescript.git\ncd react-typescript\nnpm install\n```\n\nNow use it as a base and jump to [develop your amazing application](#develop-your-amazing-application)\n\n## Project Setup Detailed\nIf you want to learn more about the details of how that project is created (instead of using it as a base), here are the steps on how its setup from scratch:\n\n* Create a project dir:\n\n```\nmkdir your-project\ncd your-project\n```\n\n* Create `tsconfig.json`:\n\n```json\n{\n  \"compilerOptions\": {\n    \"sourceMap\": true,\n    \"module\": \"commonjs\",\n    \"esModuleInterop\": true,\n    \"resolveJsonModule\": true,\n    \"experimentalDecorators\": true,\n    \"target\": \"es5\",\n    \"jsx\": \"react\",\n    \"lib\": [\n      \"dom\",\n      \"es6\"\n    ]\n  },\n  \"include\": [\n    \"src\"\n  ],\n  \"compileOnSave\": false\n}\n```\n\n* Create `package.json`.\n\n```json\n{\n  \"name\": \"react-typescript\",\n  \"version\": \"0.0.0\",\n  \"license\": \"MIT\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/basarat/react-typescript.git\"\n  },\n  \"scripts\": {\n    \"build\": \"webpack -p\",\n    \"start\": \"webpack-dev-server -d --content-base ./public\"\n  },\n  \"dependencies\": {\n    \"@types/react\": \"16.4.10\",\n    \"@types/react-dom\": \"16.0.7\",\n    \"clean-webpack-plugin\": \"0.1.19\",\n    \"html-webpack-plugin\": \"3.2.0\",\n    \"react\": \"16.4.2\",\n    \"react-dom\": \"16.4.2\",\n    \"ts-loader\": \"4.4.2\",\n    \"typescript\": \"3.0.1\",\n    \"webpack\": \"4.16.5\",\n    \"webpack-cli\": \"3.1.0\",\n    \"webpack-dev-server\": \"3.1.5\"\n  }\n}\n```\n\n* Create a `webpack.config.js` to bundle your modules into a single `app.js` file that contains all your resources:\n\n```js\nconst { CleanWebpackPlugin } = require('clean-webpack-plugin');\nconst HtmlWebpackPlugin = require('html-webpack-plugin');\n\nmodule.exports = {\n  entry: './src/app/app.tsx',\n  plugins: [\n    new CleanWebpackPlugin({\n      cleanAfterEveryBuildPatterns: ['public/build']\n    }),\n    new HtmlWebpackPlugin({\n      template: 'src/templates/index.html'\n    }),\n  ],\n  output: {\n    path: __dirname + '/public',\n    filename: 'build/[name].[contenthash].js'\n  },\n  resolve: {\n    extensions: ['.ts', '.tsx', '.js']\n  },\n  module: {\n    rules: [\n      { test: /\\.tsx?$/, loader: 'ts-loader' }\n    ]\n  }\n}\n```\n\n* `src/templates/index.html` file. It will be used as the template for the `index.html` generated by webpack. The generated file will be in the `public` folder and and then served from your webserver: \n\n```html\n<html>\n  <body>\n      <div id=\"root\"></div>\n  </body>\n</html>\n\n```\n\n* `src/app/app.tsx` that is your frontend application entry point: \n\n```js\nimport * as React from 'react';\nimport * as ReactDOM from 'react-dom';\n\nconst Hello: React.FunctionComponent<{ compiler: string, framework: string }> = (props) => {\n  return (\n    <div>\n      <div>{props.compiler}</div>\n      <div>{props.framework}</div>\n    </div>\n  );\n}\n\nReactDOM.render(\n  <Hello compiler=\"TypeScript\" framework=\"React\" />,\n  document.getElementById(\"root\")\n);\n```\n\n# Develop your amazing application \n\n> You can get the latest packages using `npm install typescript@latest react@latest react-dom@latest @types/react@latest @types/react-dom@latest webpack@latest webpack-dev-server@latest webpack-cli@latest ts-loader@latest clean-webpack-plugin@latest html-webpack-plugin@latest --save-exact`\n\n* Do live development by running `npm start`. \n    * Visit [http://localhost:8080](http://localhost:8080)\n    * Edit the `src/app/app.tsx` (or any ts/tsx file used in some way by `src/app/app.tsx`) and application live reloads. \n    * Edit the `src/templates/index.html` and the server live reloads.\n* Build production assets by running `npm run build`. \n    * Serve the `public` folder (which contains the built assets) from your server.\n"
  },
  {
    "path": "docs/quick/library.md",
    "content": "# Creating TypeScript node modules\n\n* [A lesson on creating TypeScript node modules](https://egghead.io/lessons/typescript-create-high-quality-npm-packages-using-typescript)\n\nUsing modules written in TypeScript is super fun as you get great compile time safety and autocomplete (essentially executable documentation).\n\nTypeScript modules can be consumed both in the nodejs (as is) browser (with something like webpack).\n\nCreating a high quality TypeScript module is simple. Assume the following desired folder structure for your package:\n\n```text\npackage\n├─ package.json\n├─ tsconfig.json\n├─ src\n│  ├─ index.ts\n│  ├─ foo.ts\n│  └─ ...All your source files (Authored)\n└─ lib\n  ├─ index.d.ts.map\n  ├─ index.d.ts\n  ├─ index.js\n  ├─ foo.d.ts.map\n  ├─ foo.d.ts\n  ├─ foo.js\n  └─ ... All your compiled files (Generated)\n```\n\n* `src/index.ts`: Here you would export anything you expect to be consumed from your project. E.g `export { Foo } from './foo';`. Exporting from this file makes it available for consumption when someone does `import { /* Here */ } from 'example';`\n\n* In your `tsconfig.json`\n  * have `compilerOptions`: `\"outDir\": \"lib\"` + `\"declaration\": true` + `\"declarationMap\" : true` < This generates `.js` (JavaScript) `.d.ts` (declarations for TypeSafety) and `.d.ts.map` (enables `declaration .d.ts` => `source .ts` IDE navigation) in the lib folder.\n  * have `include: [\"src\"]` < This includes all the files from the `src` dir.\n\n* In your `package.json` have\n  * `\"main\": \"lib/index\"` < This tells to load `lib/index.js` for runtime code.\n  * `\"types\": \"lib/index\"` < This tells TypeScript to load `lib/index.d.ts` for type checking. \n\nExample package:\n* `npm install typestyle` [for TypeStyle](https://www.npmjs.com/package/typestyle)\n* Usage: `import { style } from 'typestyle';` will be completely type safe.\n\n### Managing Dependencies\n#### devDependencies\n* If your package depends on another package while you are developing it (e.g. `prettier`) you should install them as a `devDependency`. This way they will not pollute the `node_modules` of your module's consumers (as `npm i foo` does not install `devDependencies` of `foo`).\n* `typescript` is normally a `devDependency` as you only use it to build your package. The consumers can use your package with or without TypeScript.\n* If your package depends on other JavaScript authored packages and you want to use it with type safety in your project, put their types (e.g. `@types/foo`) in `devDependencies`. JavaScript types should be managed *out of bound* from the main NPM streams. The JavaScript ecosystem breaks types without semantic versioning too commonly, so if your users need types for these they should install the `@types/foo` version that works for them. If you want to guide users to install these types you can put them in `peerDependencies` mentioned next.\n\n#### peerDependencies\nIf your package depends on a package that it heavily *works with* (as opposed to *works using*) e.g. `react`, put them in `peerDependencies` just like you would with raw JS packages. To test them locally you should also put them in `devDependencies`. \n\nNow: \n* When you are developing the package you will get the version of the dependency you specified in your `devDependencies`. \n* When someone installs your package they will *not* get this dependency (as `npm i foo` does not install `devDependencies` of `foo`) but they will get a warning that they should install the missing `peerDependencies` of your package. \n\n#### dependencies\nIf your package *wraps* another package (meant for internal use even after compilation) you should put them in `dependencies`. Now when someone installs your package they will get your package + any of its dependencies.\n"
  },
  {
    "path": "docs/quick/nodejs.md",
    "content": "# TypeScript with Node.js\nTypeScript has had *first class* support for Node.js since inception. Here's how to setup a quick Node.js project:\n\n> Note: many of these steps are actually just common practice Node.js setup steps\n\n1. Setup a Node.js project `package.json`. Quick one : `npm init -y`\n1. Add TypeScript (`npm install typescript --save-dev`)\n1. Add `node.d.ts` (`npm install @types/node --save-dev`)\n1. Init a `tsconfig.json` for TypeScript options with a few key options in your tsconfig.json (`npx tsc --init --rootDir src --outDir lib --esModuleInterop --resolveJsonModule --lib es6,dom  --module commonjs`)\n\nThat's it! Fire up your IDE (e.g. `code .`) and play around. Now you can use all the built in node modules (e.g. `import * as fs from 'fs';`) with all the safety and developer ergonomics of TypeScript! \n\nAll your TypeScript code goes in `src` and the generated JavaScript goes in `lib`. \n\n## Bonus: Live compile + run\n* Add `ts-node` which we will use for live compile + run in node (`npm install ts-node --save-dev`)\n* Add `nodemon` which will invoke `ts-node` whenever a file is changed (`npm install nodemon --save-dev`)\n\nNow just add a `script` target to your `package.json` based on your application entry e.g. assuming its `index.ts`:\n\n```json\n  \"scripts\": {\n    \"start\": \"npm run build:live\",\n    \"build\": \"tsc -p .\",\n    \"build:live\": \"nodemon --watch 'src/**/*.ts' --exec \\\"ts-node\\\" src/index.ts\"\n  },\n```\n\nSo you can now run `npm start` and as you edit `index.ts`:\n\n* nodemon reruns its command (ts-node)\n* ts-node transpiles automatically picking up tsconfig.json and the installed TypeScript version,\n* ts-node runs the output JavaScript through Node.js.\n\nAnd when you are ready to deploy your JavaScript application run `npm run build`.\n\n\n## Bonus points\n\nSuch NPM modules work just fine with browserify (using tsify) or webpack (using ts-loader).\n"
  },
  {
    "path": "docs/rest-parameters.md",
    "content": "### Rest Parameters\nRest parameters (denoted by `...argumentName` for the last argument) allow you to quickly accept multiple arguments in your function and get them as an array. This is demonstrated in the below example.\n\n```ts\nfunction iTakeItAll(first, second, ...allOthers) {\n    console.log(allOthers);\n}\niTakeItAll('foo', 'bar'); // []\niTakeItAll('foo', 'bar', 'bas', 'qux'); // ['bas','qux']\n```\n\nRest parameters can be used in any function be it `function`/`()=>`/`class member`.\n"
  },
  {
    "path": "docs/spread-operator.md",
    "content": "### Spread Operator\n\nThe main objective of the spread operator is to *spread* the elements of an array or object. This is best explained with examples.\n\n#### Apply\nA common use case is to spread an array into the function arguments. Previously you would need to use `Function.prototype.apply`:\n\n```ts\nfunction foo(x, y, z) { }\nvar args = [0, 1, 2];\nfoo.apply(null, args);\n```\n\nNow you can do this simply by prefixing the arguments with `...` as shown below:\n\n```ts\nfunction foo(x, y, z) { }\nvar args = [0, 1, 2];\nfoo(...args);\n```\n\nHere we are *spreading* the `args` array into positional `arguments`.\n\n#### Destructuring\nWe've already seen one usage of this in *destructuring*:\n\n```ts\nvar [x, y, ...remaining] = [1, 2, 3, 4];\nconsole.log(x, y, remaining); // 1,2,[3,4]\n```\nThe motivation here is to simply make it easy for you to capture the remaining elements of an array when destructuring.\n\n#### Array Assignment\nThe spread operator allows you to easily place an *expanded version* of an array into another array. This is demonstrated in the example below:\n\n```ts\nvar list = [1, 2];\nlist = [...list, 3, 4];\nconsole.log(list); // [1,2,3,4]\n```\n\nYou can put the expanded array in at any position, and get the effect you'd expect:\n\n```ts\nvar list = [1, 2];\nlist = [0, ...list, 4];\nconsole.log(list); // [0,1,2,4]\n```\n\n#### Object spread\nYou can also spread an object into another object. A common use case is to simply add a property to an object without mutating the original:\n\n```ts\nconst point2D = {x: 1, y: 2};\n/** Create a new object by using all the point2D props along with z */\nconst point3D = {...point2D, z: 3};\n```\n\nFor objects, the order of where you put the spread matters.  This works something like `Object.assign`, and does what you'd expect: what comes first is 'overridden' by what comes later:\n\n```ts\nconst point2D = {x: 1, y: 2};\nconst anotherPoint3D = {x: 5, z: 4, ...point2D};\nconsole.log(anotherPoint3D); // {x: 1, y: 2, z: 4}\nconst yetAnotherPoint3D = {...point2D, x: 5, z: 4}\nconsole.log(yetAnotherPoint3D); // {x: 5, y: 2, z: 4}\n```\n\nAnother common use case is a simple shallow extend:\n\n```ts\nconst foo = {a: 1, b: 2, c: 0};\nconst bar = {c: 1, d: 2};\n/** Merge foo and bar */\nconst fooBar = {...foo, ...bar};\n// fooBar is now {a: 1, b: 2, c: 1, d: 2}\n```\n\n#### Summary\n`apply` is something that you often use in JavaScript, so it's good to have a better syntax where you don't have that ugly `null` for the `this` argument. Also having a dedicated syntax for moving arrays out of (destructuring) or into (assignment) other arrays provides a neat syntax for when you are doing array processing on partial arrays.\n\n\n[](https://github.com/Microsoft/TypeScript/pull/1931)\n"
  },
  {
    "path": "docs/staging/async-await.md",
    "content": "### Async - Await\n"
  },
  {
    "path": "docs/staging/generators.md",
    "content": "### Generators\nAlso called `function *`, generators allow you to create functions whose execution can be paused and then later resumed maintaining the state between pause-resume transitions. The value returned from a generator is called an `iterator` and can be used to control this `pause-resume` transition.\n\nHere is a simple example of a generator function that generates an *infinite* list of whole numbers.\n\n```ts\nfunction* wholeNumbers() {\n    var current = 0;\n    while(true) {\n        yield current++;\n    }\n}\n```\n\nThe `yield` contextual keyword is used to return control from a generator (effectively pausing function execution) along with an optional value (here `current`). You can get access to this value using the `iterator`'s `.next()` member function, this is shown below:\n\n```ts\nfunction* wholeNumbers() {\n    var current = 0;\n    while(true) {\n        yield current++;\n    }\n}\nvar iterator = wholeNumbers();\nconsole.log(iterator.next()); // 0\nconsole.log(iterator.next()); // 1\nconsole.log(iterator.next()); // 2\n// so on till infinity....\n```\n\nNow that you have seen `function*`, `yield` and `.next()` we can dig deeper.\n\n#### Catching Errors\nAny errors thrown (intentionally using `throw` or unintentionally due to error) from the generator can be caught using `try/catch` just like normal function executions. This is demonstrated below:\n\n```ts\nfunction* wholeNumbers() {\n    var current = 0;\n    while(true) {\n      if (current === 3)\n        throw new Error('3 is the magic number');\n      else\n        yield current++;\n    }\n}\nvar iterator = wholeNumbers();\nconsole.log(iterator.next()); // 0\nconsole.log(iterator.next()); // 1\nconsole.log(iterator.next()); // 2\ntry {\n    console.log(iterator.next()); // Will throw an error\n}\ncatch(ex) {\n    console.log(ex.message); // 3 is the magic number\n}\n```\n\n#### Controlling function execution externally\nThe iterator returned from the generator function can be used to control the state *inside* the generator function as well.\n\n// TODO: example\n"
  },
  {
    "path": "docs/state/mobx.md",
    "content": "## MobX \n\n> [PRO Egghead course on MobX TypeScript React](https://egghead.io/courses/develop-react-applications-with-mobx-and-typescript)\n\n"
  },
  {
    "path": "docs/styleguide/sample.js",
    "content": "\"use strict\";\nvar formatting;\n(function (formatting) {\n    var FooVar;\n    function BarFunc() { }\n})(formatting || (formatting = {}));\nvar asdfasdf;\n(function (asdfasdf) {\n    var Foo = (function () {\n        function Foo() {\n        }\n        Foo.prototype.baz = function () { };\n        return Foo;\n    }());\n})(asdfasdf || (asdfasdf = {}));\n"
  },
  {
    "path": "docs/styleguide/sample.ts",
    "content": "export var test;\n\nnamespace formatting {\n    var FooVar;\n    function BarFunc() { }\n}\n\nnamespace asdfasdf {\n    class Foo {\n        bar: number;\n        baz() { }\n    }\n}\n"
  },
  {
    "path": "docs/styleguide/styleguide.md",
    "content": "# TypeScript Style Guide and Coding Conventions\n\n> An unofficial TypeScript Style Guide\n\nPeople have asked me for my opinions on this. Personally I don't enforce these a lot on my teams and projects but it does help to have these mentioned as a tiebreaker when someone feels the need to have such strong consistency. There are other things that I feel much more strongly about and those are covered in the [tips chapter](../tips/main.md) (e.g. type assertion is bad, property setters are bad) 🌹.\n\nKey Sections:\n\n* [Variable](#variable-and-function)\n* [Class](#class)\n* [Interface](#interface)\n* [Type](#type)\n* [Namespace](#namespace)\n* [Enum](#enum)\n* [`null` vs. `undefined`](#null-vs-undefined)\n* [Formatting](#formatting)\n* [Single vs. Double Quotes](#quotes)\n* [Tabs vs. Spaces](#spaces)\n* [Use semicolons](#semicolons)\n* [Annotate Arrays as `Type[]`](#array)\n* [File Names](#filename)\n* [`type` vs `interface`](#type-vs-interface)\n* [`==` or `===`](#-or-)\n\n## Variable and Function\n* Use `camelCase` for variable and function names\n\n> Reason: Conventional JavaScript\n\n**Bad**\n```ts\nvar FooVar;\nfunction BarFunc() { }\n```\n**Good**\n```ts\nvar fooVar;\nfunction barFunc() { }\n```\n\n## Class\n* Use `PascalCase` for class names.\n\n> Reason: This is actually fairly conventional in standard JavaScript.\n\n**Bad**\n```ts\nclass foo { }\n```\n**Good**\n```ts\nclass Foo { }\n```\n* Use `camelCase` of class members and methods\n\n> Reason: Naturally follows from variable and function naming convention.\n\n**Bad**\n```ts\nclass Foo {\n    Bar: number;\n    Baz() { }\n}\n```\n**Good**\n```ts\nclass Foo {\n    bar: number;\n    baz() { }\n}\n```\n## Interface\n\n* Use `PascalCase` for name.\n\n> Reason: Similar to class\n\n* Use `camelCase` for members.\n\n> Reason: Similar to class\n\n* **Don't** prefix with `I`\n\n> Reason: Unconventional. `lib.d.ts` defines important interfaces without an `I` (e.g. Window, Document etc).\n\n**Bad**\n```ts\ninterface IFoo {\n}\n```\n**Good**\n```ts\ninterface Foo {\n}\n```\n\n## Type\n\n* Use `PascalCase` for name.\n\n> Reason: Similar to class\n\n* Use `camelCase` for members.\n\n> Reason: Similar to class\n\n\n## Namespace\n\n* Use `PascalCase` for names\n\n> Reason: Convention followed by the TypeScript team. Namespaces are effectively just a class with static members. Class names are `PascalCase` => Namespace names are `PascalCase`\n\n**Bad**\n```ts\nnamespace foo {\n}\n```\n**Good**\n```ts\nnamespace Foo {\n}\n```\n\n## Enum\n\n* Use `PascalCase` for enum names\n\n> Reason: Similar to Class. Is a Type.\n\n**Bad**\n```ts\nenum color {\n}\n```\n**Good**\n```ts\nenum Color {\n}\n```\n\n* Use `PascalCase` for enum member\n\n> Reason: Convention followed by TypeScript team i.e. the language creators e.g `SyntaxKind.StringLiteral`. Also helps with translation (code generation) of other languages into TypeScript.\n\n**Bad**\n```ts\nenum Color {\n    red\n}\n```\n**Good**\n```ts\nenum Color {\n    Red\n}\n```\n\n## Null vs. Undefined\n\n* Prefer not to use either for explicit unavailability\n\n> Reason: these values are commonly used to keep a consistent structure between values. In TypeScript you use *types* to denote the structure\n\n**Bad**\n```ts\nlet foo = { x: 123, y: undefined };\n```\n**Good**\n```ts\nlet foo: { x: number, y?: number } = { x:123 };\n```\n\n* Use `undefined` in general (do consider returning an object like `{valid:boolean, value?:Foo}` instead)\n\n**Bad**\n```ts\nreturn null;\n```\n**Good**\n```ts\nreturn undefined;\n```\n\n* Use `null` where it's a part of the API or conventional\n\n> Reason: It is conventional in Node.js e.g. `error` is `null` for NodeBack style callbacks.\n\n**Bad**\n```ts\ncb(undefined)\n```\n**Good**\n```ts\ncb(null)\n```\n\n* Use *truthy* check for **objects** being `null` or `undefined`\n\n**Bad**\n```ts\nif (error === null)\n```\n**Good**\n```ts\nif (error)\n```\n\n* Use `== null` / `!= null` (not `===` / `!==`) to check for `null` / `undefined` on primitives as it works for both `null`/`undefined` but not other falsy values (like `''`, `0`, `false`) e.g.\n\n**Bad**\n```ts\nif (error !== null) // does not rule out undefined\n```\n**Good**\n```ts\nif (error != null) // rules out both null and undefined\n```\n\n## Formatting\nThe TypeScript compiler ships with a very nice formatting language service. Whatever output it gives by default is good enough to reduce the cognitive overload on the team.\n\nUse [`tsfmt`](https://github.com/vvakame/typescript-formatter) to automatically format your code on the command line. Also, your IDE (atom/vscode/vs/sublime) already has formatting support built-in.\n\nExamples:\n```ts\n// Space before type i.e. foo:<space>string\nconst foo: string = \"hello\";\n```\n\n## Quotes\n\n* Prefer single quotes (`'`) unless escaping.\n\n> Reason: More JavaScript teams do this (e.g. [airbnb](https://github.com/airbnb/javascript), [standard](https://github.com/feross/standard), [npm](https://github.com/npm/npm), [node](https://github.com/nodejs/node), [google/angular](https://github.com/angular/angular/), [facebook/react](https://github.com/facebook/react)). It's easier to type (no shift needed on most keyboards). [Prettier team recommends single quotes as well](https://github.com/prettier/prettier/issues/1105)\n\n> Double quotes are not without merit: Allows easier copy paste of objects into JSON. Allows people to use other languages to work without changing their quote character. Allows you to use apostrophes e.g. `He's not going.`. But I'd rather not deviate from where the JS Community is fairly decided.\n\n* When you can't use double quotes, try using back ticks (\\`).\n\n> Reason: These generally represent the intent of complex enough strings.\n\n## Spaces\n\n* Use `2` spaces. Not tabs.\n\n> Reason: More JavaScript teams do this (e.g. [airbnb](https://github.com/airbnb/javascript), [idiomatic](https://github.com/rwaldron/idiomatic.js), [standard](https://github.com/feross/standard), [npm](https://github.com/npm/npm), [node](https://github.com/nodejs/node), [google/angular](https://github.com/angular/angular/), [facebook/react](https://github.com/facebook/react)). The TypeScript/VSCode teams use 4 spaces but are definitely the exception in the ecosystem.\n\n## Semicolons\n\n* Use semicolons.\n\n> Reasons: Explicit semicolons helps language formatting tools give consistent results. Missing ASI (automatic semicolon insertion) can trip new devs e.g. `foo() \\n (function(){})` will be a single statement (not two). TC39 [warning on this as well](https://github.com/tc39/ecma262/pull/1062). Example teams: [airbnb](https://github.com/airbnb/javascript), [idiomatic](https://github.com/rwaldron/idiomatic.js), [google/angular](https://github.com/angular/angular/), [facebook/react](https://github.com/facebook/react), [Microsoft/TypeScript](https://github.com/Microsoft/TypeScript/).\n\n## Array\n\n* Annotate arrays as `foos: Foo[]` instead of `foos: Array<Foo>`.\n\n> Reasons: It's easier to read. It's used by the TypeScript team. Makes easier to know something is an array as the mind is trained to detect `[]`.\n\n## Filename\nName files with `camelCase`. E.g. `utils.ts`, `map.ts` etc.\n\n> Reason: Conventional across many JS teams.\n\nWhen the file exports a component and your framework (like React) wants component to be PascalCased, use pascal case file name to match e.g. `Accordion.tsx`, `MyControl.tsx`. \n\n> Reason: Helps with consistency (little overthought required) and its what the ecosystem is doing.\n\n## type vs. interface\n\n* Use `type` when you *might* need a union or intersection:\n\n```\ntype Foo = number | { someProperty: number }\n```\n* Use `interface` when you want `extends` or `implements` e.g.\n\n```\ninterface Foo {\n  foo: string;\n}\ninterface FooBar extends Foo {\n  bar: string;\n}\nclass X implements FooBar {\n  foo: string;\n  bar: string;\n}\n```\n* Otherwise use whatever makes you happy that day. I use [type](https://www.youtube.com/watch?v=IXAT3If0pGI)\n\n## `==` or `===`\nBoth are [mostly safe for TypeScript users](https://www.youtube.com/watch?v=vBhRXMDlA18). I use `===` as that is what is used in the TypeScript codebase. \n\n"
  },
  {
    "path": "docs/styleguide/tsconfig.json",
    "content": "{}\n"
  },
  {
    "path": "docs/template-strings.md",
    "content": "### Template Literals (Template Strings)\nSyntactically these are strings that use backticks ( i.e. \\` ) instead of single (') or double (\") quotes. The motivation of Template Literals is three fold:\n\n* String Interpolation\n* Multiline Strings\n* Tagged Templates\n\n#### String Interpolation\nAnother common use case is when you want to generate some string out of some static strings + some variables. For this you would need some *templating logic* and this is where *template strings* originally got their name from. They have since been officially renamed to *template literals*. Here's how you would potentially generate an html string previously:\n\n```ts\nvar lyrics = 'Never gonna give you up';\nvar html = '<div>' + lyrics + '</div>';\n```\nNow with template literals you can just do:\n\n```ts\nvar lyrics = 'Never gonna give you up';\nvar html = `<div>${lyrics}</div>`;\n```\n\nNote that any placeholder inside the interpolation (`${` and `}`) is treated as a JavaScript expression and evaluated as such e.g. you can do fancy math.\n\n```ts\nconsole.log(`1 and 1 make ${1 + 1}`);\n```\n\n#### Multiline Literals\nEver wanted to put a newline in a JavaScript string? Perhaps you wanted to embed some lyrics? You would have needed to *escape the literal newline* using our favorite escape character `\\`, and then put a new line into the string manually `\\n` at the next line. This is shown below:\n\n```ts\nvar lyrics = \"Never gonna give you up \\\n\\nNever gonna let you down\";\n```\n\nWith TypeScript you can just use a template string:\n\n```ts\nvar lyrics = `Never gonna give you up\nNever gonna let you down`;\n```\n\n#### Tagged Templates\n\nYou can place a function (called a `tag`) before the template string and it gets the opportunity to pre process the template string literals plus the values of all the placeholder expressions and return a result. A few notes:\n* All the static literals are passed in as an array for the first argument.\n* All the values of the placeholders expressions are passed in as the remaining arguments. Most commonly you would just use rest parameters to convert these into an array as well.\n\nHere is an example where we have a tag function (named `htmlEscape`) that escapes the html from all the placeholders:\n\n```ts\nvar say = \"a bird in hand > two in the bush\";\nvar html = htmlEscape `<div> I would just like to say : ${say}</div>`;\n\n// a sample tag function\nfunction htmlEscape(literals: TemplateStringsArray, ...placeholders: string[]) {\n    let result = \"\";\n\n    // interleave the literals with the placeholders\n    for (let i = 0; i < placeholders.length; i++) {\n        result += literals[i];\n        result += placeholders[i]\n            .replace(/&/g, '&amp;')\n            .replace(/\"/g, '&quot;')\n            .replace(/'/g, '&#39;')\n            .replace(/</g, '&lt;')\n            .replace(/>/g, '&gt;');\n    }\n\n    // add the last literal\n    result += literals[literals.length - 1];\n    return result;\n}\n```\n> Note: You can annotate `placeholders` to be any `[]`. Whatever you annotate it as, TypeScript will type check to make sure the placeholders used to call the tag match the annotation. For example if you expect to deal with `string` or `number`s you can annotate `...placeholders:(string | number)[]`\n\n#### Generated JS\nFor pre ES6 compile targets the code is fairly simple. Multiline strings become escaped strings. String interpolation becomes *string concatenation*. Tagged Templates become function calls.\n\n#### Summary\nMultiline strings and string interpolation are just great things to have in any language. It's great that you can now use them in your JavaScript (thanks TypeScript!). Tagged templates allow you to create powerful string utilities.\n"
  },
  {
    "path": "docs/testing/cypress.md",
    "content": "# Why Cypress\nCypress is a great E2E testing tool. Here are a few great reasons to consider it:\n\n* Isolated installation possible.\n* Ships with TypeScript support out of the box.\n* Provides a nice interactive google chrome debug experience. This is very similar to how UI devs mostly work manually.\n* Has command - execution separation which allows for more powerful debugging and test stability (more on this below).\n* Has implicit assertions to provide more meaningful debug experience with less brittle tests (more on this in the tips below).\n* Provides the ability to mock out and observe backend XHRs easily without changing your application code (more on this in the tips below).\n\n## Installation\nThe steps provided in this installation process will give you a nice `e2e` folder that you can copy/paste or as boiler plate for your organization.\n\n> Same steps presented in a video format over at my [youtube channel](https://www.youtube.com/watch?v=n3SvvZSWwfM).\n\nCreate an e2e directory, install cypress, TypeScript and setup the typescript and cypress config files:\n\n```sh\nmkdir e2e\ncd e2e\nnpm init -y\nnpm install cypress typescript\nnpx tsc --init --types cypress --lib dom,es6\necho {} > cypress.json \n```\n\n> Here are a few reasons for creating a separate `e2e` folder especially for cypress:\n* Creating a separate directory or `e2e` makes it easier to isolate its `package.json` dependencies from the rest of your project. This results in less dependency conflicts.\n* Testing frameworks have a habit of polluting the global namespace with stuff like `describe` `it` `expect`. It is best to keep the e2e `tsconfig.json` and `node_modules` in this special `e2e` folder to prevent global type definition conflicts.\n\nAdd a few scripts to the `e2e/package.json` file:\n\n```json\n  \"scripts\": {\n    \"cypress:open\": \"cypress open\",\n    \"cypress:run\": \"cypress run\"\n  },\n```\n\nWrite your first test under `cypress/integration/basic.ts`: \n\n```ts\nit('should perform basic google search', () => {\n  cy.visit('https://google.com');\n  cy.get('[name=\"q\"]')\n    .type('subscribe')\n    .type('{enter}');\n});\n```\n\nNow run `npm run cypress:open` during development and `npm run cypress:run` on your build server 🌹\n\n## More description of key Files\nUnder the `e2e` folder you now have these files:\n\n* `/cypress.json`: Configure cypress. The default is empty and that is all you need.\n* `/cypress` Subfolders:\n    * `/integration`: All your tests.\n        * Feel free to create tests under subfolders for better organization e.g. `/someFeatureFolder/something.spec.ts`.\n\n## First test\n* create a file `/cypress/integration/first.ts` with the following contents:\n\n```ts\ndescribe('google search', () => {\n  it('should work', () => {\n    cy.visit('http://www.google.com');\n    cy.get('#lst-ib').type('Hello world{enter}')\n  });\n});\n```\n\n## Running in development\nOpen the cypress IDE using the following command.\n\n```sh\nnpm run cypress:open\n```\n\nAnd select a test to run.\n\n## Running on a build server\n\nYou can run cypress tests in ci mode using the following command.\n\n```sh\nnpm run cypress:run\n```\n\n## Tip: Sharing code between UI and test\nCypress tests are compiled / packed and run in the browser. So feel free to import any project code into your test.\n\nFor example you can share Id values between UI and Tests to make sure the CSS selectors don't break:\n\n```js\nimport { Ids } from '../../../src/app/constants';\n\n// Later\ncy.get(`#${Ids.username}`)\n  .type('john')\n```\n\n## Tip: Creating Page Objects\nCreating objects that provide a convenient handle for all the interactions that various tests need to do with a page is a common testing convention. You can create page objects using TypeScript classes with getters and methods e.g.\n\n```js\nimport { Ids } from '../../../src/app/constants';\n\nclass LoginPage {\n  visit() {\n    cy.visit('/login');\n  }\n\n  get username() {\n    return cy.get(`#${Ids.username}`);\n  }\n}\nconst page = new LoginPage();\n\n// Later\npage.visit();\n\npage.username.type('john');\n\n```\n\n## Tip: Explicit assertion\nCypress ships with (built in) chai and chai-query assertion libraries to help testing webpages. You use them with `.should` command passing in the chainer as a string, replacing `.to.foo` with `should('foo')` e.g. with chai-jquery you would `expect($(#foo)).to.have.text('something')`, with cypress you would `cy.get('#foo').should('have.text', 'something')`:\n\n```\ncy.get('#foo')\n  .should('have.text', 'something')\n```\n> You get intellisense for `should` chainers as cypress ships with correct TypeScript definitions 👍🏻\n\nThe complete list of chainers is available here : https://docs.cypress.io/guides/references/assertions.html\n\nIf you want something complex you can even use `should(callback)` and e.g.\n\n```\ncy.get('div')\n  .should(($div) => {\n    expect($div).to.have.length(1);\n    expect($div[0].className).to.contain('heading');\n  })\n// This is just an example. Normally you would `.should('have.class', 'heading')\n```\n\n> TIP: cypress with do automatic retries on the callback as well, so they are just as flake free as standard string chainers.\n\n## Tip: Commands and Chaining\nEvery function call in a cypress chain is a `command`. The `should` command is an assertion. It is conventional to start distinct *category* of chains and actions separately e.g.\n\n```ts\n// Don't do this\ncy.get(/**something*/)\n  .should(/**something*/)\n  .click()\n  .should(/**something*/)\n  .get(/**something else*/)\n  .should(/**something*/)\n\n// Prefer separating the two gets\ncy.get(/**something*/)\n  .should(/**something*/)\n  .click()\n  .should(/**something*/)\n\ncy.get(/**something else*/)\n  .should(/**something*/)\n```\n\nSome other libraries *evaluate and run* the code at the same time. Those libraries force you to have a single chain which can be nightmare to debug with selectors and assertions mingled in.\n\nCypress commands are essentially *declarations* to the cypress runtime to execute the commands later. Simple words: Cypress makes it easier.\n\n## Tip: Using `contains` for easier querying\n\nThe following shows an example:\n\n```\ncy.get('#foo')\n  // Once #foo is found the following:\n  .contains('Submit')\n  .click()\n  // ^ will continue to search for something that has text `Submit` and fail if it times out.\n  // ^ After it is found trigger a click on the HTML Node that contained the text `Submit`.\n```\n\n## Tip: Smart delays and retries\nCypress will automatically wait (and retry) for many async things e.g.\n```\n// If there is no request against the `foo` alias cypress will wait for 4 seconds automatically\ncy.wait('@foo')\n// If there is no element with id #foo cypress will wait for 4 seconds automatically and keep retrying\ncy.get('#foo')\n```\nThis keeps you from having to constantly add arbitrary timeout (and retry) logic in your test code flow.\n\n## Tip: Implicit assertion\nCypress has a concept of implicit assertion. These kick in if a future command is erroring because of a previous command. E.g. the following will error at `contains` (after automatic retries of course) as nothing found can get `click`ed:\n\n```ts\ncy.get('#foo')\n  // Once #foo is found the following:\n  .contains('Submit')\n  .click()\n  // ^ Error: #foo does not have anything that `contains` `'Submit'`\n```\n\nIn traditional frameworks you would get a horrible error like `click` doesn't exist on `null`. In Cypress you get a nice error `#foo` does not contain `Submit`. This error is a form of an implicit assertion.\n\n## Tip: Waiting for an HTTP request\nA lot of tests have been traditionally brittle due to all the arbitrary timeouts needed for XHRs that an application makes. `cy.server` makes it easy to\n* create an alias for backend calls\n* wait for them to occur\n\ne.g.\n\n```ts\ncy.server()\n  .route('POST', 'https://example.com/api/application/load')\n  .as('load') // create an alias\n\n// Start test\ncy.visit('/')\n\n// wait for the call\ncy.wait('@load')\n\n// Now the data is loaded\n```\n\n## Tip: Mocking an HTTP request response\nYou can also easily mock out a request response using `route`:\n```ts\ncy.server()\n  .route('POST', 'https://example.com/api/application/load', /* Example payload response */{success:true});\n```\n\n### Tip: Asserting an Http request response\nYou can assert requests without mocking using `route` `onRequest` / `onResponse` e.g.\n\n```ts\ncy.route({\n  method: 'POST',\n  url: 'https://example.com/api/application/load',\n  onRequest: (xhr) => {\n    // Example assertion\n    expect(xhr.request.body.data).to.deep.equal({success:true});\n  }\n})\n```\n\n## Tip: Mocking time\nYou can use `wait` to pause a test for some time e.g. to test an automatic \"you are about to be logged out\" notification screen:\n\n```ts\ncy.visit('/');\ncy.wait(waitMilliseconds);\ncy.get('#logoutNotification').should('be.visible');\n```\n\nHowever, it is recommended to mock time using `cy.clock` and forwarding time using `cy.tick` e.g.\n\n```ts\ncy.clock();\n\ncy.visit('/');\ncy.tick(waitMilliseconds);\ncy.get('#logoutNotification').should('be.visible');\n```\n\n## Tip: Unit testing application code\nYou can also use cypress to unit test your application code in isolation e.g.\n\n```js\nimport { once } from '../../../src/app/utils';\n\n// Later\nit('should only call function once', () => {\n  let called = 0;\n  const callMe = once(()=>called++);\n  callMe();\n  callMe();\n  expect(called).to.equal(1);\n});\n```\n\n## Tip: Mocking in unit testing\nIf you are unit testing modules in your application you can provide mocks using `cy.stub` e.g. if you want to ensure that `navigate` is called in a function `foo`:\n\n* `foo.ts`\n\n```ts\nimport { navigate } from 'takeme';\n\nexport function foo() {\n  navigate('/foo');\n}\n```\n\n* You can do this as in `some.spec.ts`:\n\n```ts\n/// <reference types=\"cypress\"/>\n\nimport { foo } from '../../../src/app/foo';\nimport * as takeme from 'takeme';\n\ndescribe('should work', () => {\n  it('should stub it', () => {\n    cy.stub(takeme, 'navigate');\n    foo();\n    expect(takeme.navigate).to.have.been.calledWith('/foo');\n  });\n});\n```\n\n## Tip: Command - execution separation\nWhen you invoke a cypress command (or assertion) e.g. `cy.get('#something')`, the function immediately returns without actually carrying out the action. What it does do, is informs the cypress test runner that you will need to carry out (execute) an action (in this case a `get`) at some point.\n\nYou are basically building a command list that the runner will then go ahead and execute. You can verify this command - execution separation with a simple test, observe that you will see the `start / between / end` `console.log` statements execute immediately before the runner starts *executing* the commands:\n\n```ts\n/// <reference types=\"cypress\"/>\n\ndescribe('Hello world', () => {\n  it('demonstrate command - execution separation', () => {\n    console.log('start');\n    cy.visit('http://www.google.com');\n    console.log('between');\n    cy.get('.gLFyf').type('Hello world');\n    console.log('end');\n  });\n});\n```\n\nThis command execution separation has two big benefits:\n* The runner can execute the commands in a *flake resistant* manner with automatic retries and implicit assertions.\n* Allows you to write asynchronous code in a synchronous fashion without having to do a constant *chaining* which results in difficult to maintain code.\n\n## Tip: Breakpoint\nThe automatic snapshots + command log generated by the cypress test are great for debugging. That said you can pause test execution if you want.\n\nFirst make sure you have chrome developer tools (lovingly called dev tools) open in the test runner (`CMD + ALT + i` on mac / `F12` on windows). Once the dev tools are open you can re-run the test and the dev tools will stay open. If you have the dev tools open, you can pause test execution in two ways:\n\n* Application code breakpoints: Use a `debugger` statement in your application code and the test runner will stop on that just like standard web development.\n* Test code breakpoints: You can use the `.debug()` command and cypress test execution will stop at it. Alternatively you can use a `debugger` statement in a `.then` command callback to cause a pause. e.g `.then(() => { debugger })`. You can even use it to grab some element `cy.get('#foo').then(($ /* a reference to the dom element */) => { debugger; })` or a network call e.g. `cy.request('https://someurl').then((res /* network response */) => { debugger });`. However idiomatic way is `cy.get('#foo').debug()` and then when the test runner is paused on `debug` you can click on the `get` in the command log to automatically `console.log` any information you might need about the `.get('#foo')` command (and similarly for any other commands you want to debug).\n\n## Tip: Start server and test\nIf you need to start a local server before your tests can run you can add `start-server-and-test` https://github.com/bahmutov/start-server-and-test as a dependency. It takes the following arguments\n* an npm script to *run* the server (aka server)\n* an endpoint to check if the server has booted up (aka start)\n* an npm script to initiate the testing (aka test)\n\nExample package.json:\n```json\n{\n    \"scripts\": {\n        \"start-server\": \"npm start\",\n        \"run-tests\": \"mocha e2e-spec.js\",\n        \"ci\": \"start-server-and-test start-server http://localhost:8080 run-tests\"\n    }\n}\n```\n\n## Resources\n* Website: https://www.cypress.io/\n* Write your first cypress test (gives a nice tour of the cypress IDE) : https://docs.cypress.io/guides/getting-started/writing-your-first-test.html\n* Setting up a CI environment (e.g. the provided docker image that works out of the box with `cypress run`): https://docs.cypress.io/guides/guides/continuous-integration.html\n* Recipes (Lists recipes with descriptions. Click on headings to navigate to the source code for the recipe): https://docs.cypress.io/examples/examples/recipes.html\n* Visual Testing : https://docs.cypress.io/guides/tooling/visual-testing.html\n* Optionally set a `baseUrl` in cypress.json to [prevent an initial reload that happens after first `visit`.](https://github.com/cypress-io/cypress/issues/2542)\n* Code coverage with cypress: [Webcast](https://www.youtube.com/watch?v=C8g5X4vCZJA)\n"
  },
  {
    "path": "docs/testing/intro.md",
    "content": "# Testing\nTypeScript can be used with any JavaScript testing framework that you want. In the worst case you can always do a simple `TypeScript -> JavaScript` transform and go your merry way. \n\nThat said, in this section look at options that we have enjoyed greatly 🌹\n"
  },
  {
    "path": "docs/testing/jest.md",
    "content": "# Using Jest with TypeScript\n\n> [Pro egghead lesson on Jest / TypeScript](https://egghead.io/lessons/typescript-getting-started-with-jest-using-typescript)\n\nNo testing solution out there is perfect. That said, jest is an excellent unit testing option which provides great TypeScript support.\n\n> Note: We assume you start off with a simple node package.json setup. Also all TypeScript files should be in a `src` folder which is always recommended (even without Jest) for a clean project setup.\n\n## Step 1: Install\n\nInstall the following using npm:\n\n```shell\nnpm i jest @types/jest ts-jest typescript -D\n```\n\nExplanation:\n\n* Install `jest` framework (`jest`)\n* Install the types for `jest` (`@types/jest`)\n* Install the TypeScript preprocessor for jest (`ts-jest`) which allows jest to transpile TypeScript on the fly and have source-map support built in.\n* Install the TypeScript compiler ('typescript') which is prerequisite for 'ts-jest'.\n* Save all of these to your dev dependencies (testing is almost always a npm dev-dependency)\n\n## Step 2: Configure Jest\n\nAdd the following `jest.config.js` file to the root of your project:\n\n```js\nmodule.exports = {\n  \"roots\": [\n    \"<rootDir>/src\"\n  ],\n  \"testMatch\": [\n    \"**/__tests__/**/*.+(ts|tsx|js)\",\n    \"**/?(*.)+(spec|test).+(ts|tsx|js)\"\n  ],\n  \"transform\": {\n    \"^.+\\\\.(ts|tsx)$\": \"ts-jest\"\n  },\n}\n```\n\n(If your `package.json` file contains `\"type\": \"module\"`, which causes Node to assume modules are in es6 format, you can convert the above to es6 format by replacing the top line to `export default { ` .)\n\nExplanation:\n\n* We always recommend having *all* TypeScript files in a `src` folder in your project. We assume this is true and specify this using the `roots` option.\n* The `testMatch` config is a glob pattern matcher for discovering .test / .spec files in ts / tsx / js format.\n* The `transform` config just tells `jest` to use `ts-jest` for ts / tsx files.\n\n## Step 3: Run tests\n\nRun `npx jest` from your project root and jest will execute any tests you have.\n\n### Optional: Add script target for npm scripts\n\nAdd `package.json`:\n\n```json\n{\n  \"test\": \"jest\"\n}\n```\n\n* This allows you to run the tests with a simple `npm t`.\n* And even in watch mode with `npm t -- --watch`.\n\n### Optional: Run jest in watch mode\n\n* `npx jest --watch`\n\n### Example\n\n* For a file `foo.ts`:\n\n    ```js\n    export const sum\n      = (...a: number[]) =>\n        a.reduce((acc, val) => acc + val, 0);\n    ```\n\n* A simple `foo.test.ts`:\n\n    ```js\n    import { sum } from '../foo';\n\n    test('basic', () => {\n      expect(sum()).toBe(0);\n    });\n\n    test('basic again', () => {\n      expect(sum(1, 2)).toBe(3);\n    });\n    ```\n\nNotes:\n\n* Jest provides the global `test` function.\n* Jest comes prebuilt with assertions in the form of the global `expect`.\n\n### Example async\n\nJest has built-in async/await support. e.g.\n\n```js\ntest('basic',async () => {\n  expect(sum()).toBe(0);\n});\n\ntest('basic again', async () => {\n  expect(sum(1, 2)).toBe(3);\n}, 1000 /* optional timeout */);\n```\n\n### Example enzyme\n\n> [Pro egghead lesson on Enzyme / Jest / TypeScript](https://egghead.io/lessons/react-test-react-components-and-dom-using-enzyme)\n\nEnzyme allows you to test react components with dom support. There are three steps to setting up enzyme:\n\n1. Install enzyme, types for enzyme, a better snapshot serializer for enzyme, enzyme-adapter-react for your react version `npm i enzyme @types/enzyme enzyme-to-json enzyme-adapter-react-16 -D`\n2. Add `\"snapshotSerializers\"` and `\"setupTestFrameworkScriptFile\"` to your `jest.config.js`:  \n\n    ```js\n    module.exports = {\n      // OTHER PORTIONS AS MENTIONED BEFORE\n\n      // Setup Enzyme\n      \"snapshotSerializers\": [\"enzyme-to-json/serializer\"],\n      \"setupFilesAfterEnv\": [\"<rootDir>/src/setupEnzyme.ts\"],\n    }\n    ```\n\n3. Create `src/setupEnzyme.ts` file.\n\n    ```js\n    import { configure } from 'enzyme';\n    import EnzymeAdapter from 'enzyme-adapter-react-16';\n    configure({ adapter: new EnzymeAdapter() });\n    ```\n\nNow here is an example react component and test:\n\n* `checkboxWithLabel.tsx`:\n\n    ```ts\n    import * as React from 'react';\n\n    export class CheckboxWithLabel extends React.Component<{\n      labelOn: string,\n      labelOff: string\n    }, {\n        isChecked: boolean\n      }> {\n      constructor(props) {\n        super(props);\n        this.state = { isChecked: false };\n      }\n\n      onChange = () => {\n        this.setState({ isChecked: !this.state.isChecked });\n      }\n\n      render() {\n        return (\n          <label>\n            <input\n              type=\"checkbox\"\n              checked={this.state.isChecked}\n              onChange={this.onChange}\n            />\n            {this.state.isChecked ? this.props.labelOn : this.props.labelOff}\n          </label>\n        );\n      }\n    }\n\n    ```\n\n* `checkboxWithLabel.test.tsx`:\n\n    ```ts\n    import * as React from 'react';\n    import { shallow } from 'enzyme';\n    import { CheckboxWithLabel } from './checkboxWithLabel';\n\n    test('CheckboxWithLabel changes the text after click', () => {\n      const checkbox = shallow(<CheckboxWithLabel labelOn=\"On\" labelOff=\"Off\" />);\n\n      // Interaction demo\n      expect(checkbox.text()).toEqual('Off');\n      checkbox.find('input').simulate('change');\n      expect(checkbox.text()).toEqual('On');\n\n      // Snapshot demo\n      expect(checkbox).toMatchSnapshot();\n    });\n    ```\n\n## Reasons why we like jest\n\n> [For details on these features see jest website](http://facebook.github.io/jest/)\n\n* Built-in assertion library.\n* Great TypeScript support.\n* Very reliable test watcher.\n* Snapshot testing.\n* Built-in coverage reports.\n* Built-in async/await support.\n"
  },
  {
    "path": "docs/tips/barrel.md",
    "content": "## Barrel\n\nA barrel is a way to rollup exports from several modules into a single convenient module. The barrel itself is a module file that re-exports selected exports of other modules.\n\nImagine the following class structure in a library: \n\n```ts\n// demo/foo.ts\nexport class Foo {}\n\n// demo/bar.ts\nexport class Bar {}\n\n// demo/baz.ts\nexport class Baz {}\n```\n\nWithout a barrel, a consumer would need three import statements:\n\n```ts\nimport { Foo } from '../demo/foo';\nimport { Bar } from '../demo/bar';\nimport { Baz } from '../demo/baz';\n```\n\nYou can instead add a barrel `demo/index.ts` containing the following: \n\n```ts\n// demo/index.ts\nexport * from './foo'; // re-export all of its exports\nexport * from './bar'; // re-export all of its exports\nexport * from './baz'; // re-export all of its exports\n```\n\nNow the consumer can import what it needs from the barrel:\n\n```ts\nimport { Foo, Bar, Baz } from '../demo'; // demo/index.ts is implied\n```\n\n### Named exports\nInstead of exporting `*`, you can choose to export the module in a name. E.g., assume that `baz.ts` has functions:\n\n```ts\n// demo/foo.ts\nexport class Foo {}\n\n// demo/bar.ts\nexport class Bar {}\n\n// demo/baz.ts\nexport function getBaz() {}\nexport function setBaz() {}\n```\n\nIf you would rather not export `getBaz` / `setBaz` from demo you can instead put them in a variable by importing them in a name and exporting that name as shown below: \n\n```ts\n// demo/index.ts\nexport * from './foo'; // re-export all of its exports\nexport * from './bar'; // re-export all of its exports\n\nimport * as baz from './baz'; // import as a name\nexport { baz }; // export the name\n```\n\nAnd now the consumer would look like: \n\n```ts\nimport { Foo, Bar, baz } from '../demo'; // demo/index.ts is implied\n\n// usage\nbaz.getBaz();\nbaz.setBaz();\n// etc. ...\n```\n"
  },
  {
    "path": "docs/tips/build-toggles.md",
    "content": "## Build Toggles\n\nIt is common to switch in JavaScript projects based on where they are being run. You can do this quite easily with webpack as it supports *dead code elimination* based on environment variables.\n\nAdd different targets in your `package.json` `scripts`:\n\n```json\n\"build:test\": \"webpack -p --config ./src/webpack.config.js\",\n\"build:prod\": \"webpack -p --define process.env.NODE_ENV='\\\"production\\\"' --config ./src/webpack.config.js\",\n```\n\nOf course I am assuming you have `npm install webpack --save-dev`. Now you can run `npm run build:test` etc.\n\nUsing this variable is super easy as well:\n\n```ts\n/**\n * This interface makes sure we don't miss adding a property to both `prod` and `test`\n */\ninterface Config {\n  someItem: string;\n}\n\n/**\n * We only export a single thing. The config.\n */\nexport let config: Config;\n\n/**\n * `process.env.NODE_ENV` definition is driven from webpack\n *\n * The whole `else` block will be removed in the emitted JavaScript\n *  for a production build\n */\nif (process.env.NODE_ENV === 'production') {\n  config = {\n    someItem: 'prod'\n  }\n  console.log('Running in prod');\n} else {\n  config = {\n    someItem: 'test'\n  }\n  console.log('Running in test');\n}\n```\n\n> We use `process.env.NODE_ENV` just because it is conventional in a lot of JavaScript libraries themselves e.g. `React`.\n"
  },
  {
    "path": "docs/tips/classesAreUseful.md",
    "content": "## Classes Are Useful\n\nIt is very common to have the following structure:\n\n```ts\nfunction foo() {\n    let someProperty;\n\n    // Some other initialization code\n\n    function someMethod() {\n        // Do some stuff with `someProperty`\n        // And potentially other things\n    }\n    // Maybe some other methods\n\n    return {\n        someMethod,\n        // Maybe some other methods\n    };\n}\n```\n\nThis is known as the *revealing module pattern* and quite common in JavaScript (taking advantage of JavaScript closure).\n\nIf you use [*file modules* (which you really should as global scope is bad)](../project/modules.md) then *your file is effectively the same*. However, there are too many cases where people will write code like the following:\n\n```ts\nlet someProperty;\n\nfunction foo() {\n   // Some initialization code\n}\nfoo(); // some initialization code\n\nsomeProperty = 123; // some more initialization\n\n// Some utility function not exported\n\n// later\nexport function someMethod() {\n\n}\n```\n\nEven though I am not a big fan of inheritance *I do find that letting people use classes helps them organize their code better*. The same developer would intuitively write the following:\n\n```ts\nclass Foo {\n    public someProperty;\n\n    constructor() {\n        // some initialization\n    }\n\n    public someMethod() {\n        // some code\n    }\n\n    private someUtility() {\n        // some code\n    }\n}\n\nexport = new Foo();\n```\n\nAnd its not just developers, creating dev tools that provide great visualizations over classes are much more common, and there is one less pattern your team needs to understand and maintain.\n\n> PS: There is nothing wrong in my opinion with *shallow* class hierarchies if they provide significant reuse and reduction in boiler plate.\n"
  },
  {
    "path": "docs/tips/create-arrays.md",
    "content": "## Creating arrays\n\nCreating an empty array is super easy: \n\n```ts\nconst foo: string[] = [];\n```\n\nIf you want an array to loop over: \n\n```ts\n[...new Array(6)]; \n```\n\nIf you want to create an array pre-filled with some content use the ES6 `Array.prototype.fill`: \n\n```ts\nconst foo: string[] = new Array(3).fill('');\nconsole.log(foo); // ['','',''];\n```\n\nIf you want to create an array of a predefined length with calls you can use the spread operator: \n\n```ts\nconst someNumbers = [...new Array(3)].map((_,i) => i * 10);\nconsole.log(someNumbers); // [0,10,20];\n```\n"
  },
  {
    "path": "docs/tips/currying.md",
    "content": "## Currying\n\nJust use a chain of fat arrow functions:\n\n```ts\n// A curried function\nlet add = (x: number) => (y: number) => x + y;\n\n// Simple usage\nadd(123)(456);\n\n// partially applied\nlet add123 = add(123);\n\n// fully apply the function\nadd123(456);\n```\n"
  },
  {
    "path": "docs/tips/defaultIsBad.md",
    "content": "## `export default` concerns\n\nConsider you have a file `foo.ts` with the following contents:\n\n```ts\nclass Foo {\n}\nexport default Foo;\n```\n\nYou would import it (in `bar.ts`) using ES6 syntax as follows:\n\n```ts\nimport Foo from \"./foo\";\n```\n\nThere are a few maintainability concerns here:\n* If you refactor `Foo` in `foo.ts` it will not rename it in `bar.ts`.\n* If you end up needing to export more stuff from `foo.ts` (which is what many of your files will have) then you have to juggle the import syntax.\n\nFor this reason I recommend simple exports + destructured import. E.g. `foo.ts`:\n\n```ts\nexport class Foo {\n}\n```\nAnd then:\n\n```ts\nimport { Foo } from \"./foo\";\n```\n\nBelow I also present a few more reasons.\n\n### Poor Discoverability\nDiscoverability is very poor for default exports. You cannot explore a module with intellisense to see if it has a default export or not.\n\nWith export default you get nothing here (maybe it does export default / maybe it doesn't `¯\\_(ツ)_/¯`):\n```\nimport /* here */ from 'something';\n```\n\nWithout export default you get a nice intellisense here: \n\n```\nimport { /* here */ } from 'something';\n```\n\n### Autocomplete \nIrrespective of if you know about the exports, you even autocomplete at this `import {/*here*/} from \"./foo\";` cursor location. Gives your developers a bit of wrist relief.\n\n### CommonJS interop\nWith `default` there is horrible experience for commonJS users who have to `const {default} = require('module/foo');` instead of `const {Foo} = require('module/foo')`. You will most likely want to rename the `default` export to something else when you import it.\n\n### Typo Protection\nYou don't get typos like one dev doing `import Foo from \"./foo\";` and another doing `import foo from \"./foo\";`\n\n### TypeScript auto-import\nAuto import quickfix works better. You use `Foo` and auto import will write down `import { Foo } from \"./foo\";` cause its a well defined name exported from a module. Some tools out there will try to magic read and *infer* a name for a default export but magic is flaky.\n\n### Re-exporting\nRe-exporting is common for the root `index` file in npm packages, and forces you to name the default export manually e.g. `export { default as Foo } from \"./foo\";` (with default) vs. `export * from \"./foo\"` (with named exports).\n\n### Dynamic Imports\nDefault exports expose themselves badly named as `default` in dynamic `import`s e.g. \n\n```ts\nconst HighCharts = await import('https://code.highcharts.com/js/es-modules/masters/highcharts.src.js');\nHighCharts.default.chart('container', { ... }); // Notice `.default`\n```\n\nMuch nicer with named exports: \n\n```ts\nconst {HighCharts} = await import('https://code.highcharts.com/js/es-modules/masters/highcharts.src.js');\nHighCharts.chart('container', { ... }); // Notice `.default`\n```\n\n\n### Needs two lines for non-class / non-function\n\nCan be one statement for function / class e.g. \n\n```ts\nexport default function foo() {\n}\n```\n\nCan be one statement for *non named / type annotated* objects e.g.: \n\n```ts\nexport default {\n  notAFunction: 'Yeah, I am not a function or a class',\n  soWhat: 'The export is now *removed* from the declaration'\n};\n```\n\nBut needs two statements otherwise:\n```ts\n// If you need to name it (here `foo`) for local use OR need to annotate type (here `Foo`)\nconst foo: Foo = {\n  notAFunction: 'Yeah, I am not a function or a class',\n  soWhat: 'The export is now *removed* from the declaration'\n};\nexport default foo;\n```\n"
  },
  {
    "path": "docs/tips/functionParameters.md",
    "content": "# Function Parameters\n\nIf you have a function that takes too many parameters, or parameters of the same type, then you might want to consider changing the function to take an object instead. \n\nConsider the following function:\n\n```ts\nfunction foo(flagA: boolean, flagB: boolean) {\n  // your awesome function body \n}\n```\n\nWith such a function definition it's quite easy to invoke it incorrectly e.g. `foo(flagB, flagA)` and you would get no help from the compiler. \n\nInstead, convert the function to take an object: \n\n```ts\nfunction foo(config: {flagA: boolean, flagB: boolean}) {\n  const {flagA, flagB} = config;\n  // your awesome function body \n}\n```\nNow the function calls will look like `foo({flagA, flagB})` which makes it much easier to spot mistakes and code review.\n\n> Note : If your function is simple enough, and you don't expect much churn, then feel free to ignore this advice 🌹.\n"
  },
  {
    "path": "docs/tips/jquery.md",
    "content": "## JQuery Tips\n\nNote: you need to install the `jquery.d.ts` file for these tips\n\n### Quickly define a new plugin \n\nJust create `jquery-foo.d.ts` with: \n\n```ts\ninterface JQuery {\n  foo: any;\n}\n```\n\nAnd now you can use `$('something').foo({whateverYouWant:'hello jquery plugin'})`\n"
  },
  {
    "path": "docs/tips/lazyObjectLiteralInitialization.md",
    "content": "## Lazy Object Literal Initialization\n\nQuite commonly in JavaScript code bases you would initialize object literals in the following manner:\n\n```ts\nlet foo = {};\nfoo.bar = 123;\nfoo.bas = \"Hello World\";\n```\n\nAs soon as you move the code to TypeScript you will start to get Errors like the following:\n\n```ts\nlet foo = {};\nfoo.bar = 123; // Error: Property 'bar' does not exist on type '{}'\nfoo.bas = \"Hello World\"; // Error: Property 'bas' does not exist on type '{}'\n```\n\nThis is because from the state `let foo = {}`, TypeScript *infers* the type of `foo` (left hand side of initializing assignment) to be the type of the right hand side `{}` (i.e. an object with no properties). So, it error if you try to assign to a property it doesn't know about.\n\n### Ideal Fix\n\nThe *proper* way to initialize an object in TypeScript is to do it in the assignment:\n\n```ts\nlet foo = {\n    bar: 123,\n    bas: \"Hello World\",\n};\n```\n\nThis is also great for code review and code maintainability purposes.\n\n> The quick fix and middle ground *lazy* initialization patterns described below suffer from *mistakenly forgetting to initialize a property*. \n\n### Quick Fix\n\nIf you have a large JavaScript code base that you are migrating to TypeScript the ideal fix might not be a viable solution for you. In that case you can carefully use a *type assertion* to silence the compiler:\n\n```ts\nlet foo = {} as any;\nfoo.bar = 123;\nfoo.bas = \"Hello World\";\n```\n\n### Middle Ground\n\nOf course using the `any` assertion can be very bad as it sort of defeats the safety of TypeScript. The middle ground fix is to create an `interface` to ensure\n\n* Good Docs\n* Safe assignment\n\nThis is shown below:\n\n```ts\ninterface Foo {\n    bar: number\n    bas: string\n}\n\nlet foo = {} as Foo;\nfoo.bar = 123;\nfoo.bas = \"Hello World\";\n```\n\nHere is a quick example that shows the fact that using the interface can save you:\n\n```ts\ninterface Foo {\n    bar: number\n    bas: string\n}\n\nlet foo = {} as Foo;\nfoo.bar = 123;\nfoo.bas = \"Hello World\";\n\n// later in the codebase:\nfoo.bar = 'Hello Stranger'; // Error: You probably misspelled `bas` as `bar`, cannot assign string to number\n```\n"
  },
  {
    "path": "docs/tips/main.md",
    "content": "# TIPs\nIn this section we present a number of tips that we have collected over the course of using TypeScript in the real world.\n"
  },
  {
    "path": "docs/tips/nominalTyping.md",
    "content": "## Nominal Typing\nThe TypeScript type system is structural [and this is one of the main motivating benefits](../why-typescript.md). However, there are real-world use cases for a system where you want two variables to be differentiated because they have a different *type name* even if they have the same structure. A very common use case is *identity* structures (which are generally just strings with semantics associated with their *name* in languages like C#/Java).\n\nThere are a few patterns that have emerged in the community. I cover them in decreasing order of personal preference:\n\n## Using literal types\n\nThis pattern uses generics and literal types: \n\n```ts\n/** Generic Id type */\ntype Id<T extends string> = {\n  type: T,\n  value: string,\n}\n\n/** Specific Id types */\ntype FooId = Id<'foo'>;\ntype BarId = Id<'bar'>;\n\n/** Optional: constructors functions */\nconst createFoo = (value: string): FooId => ({ type: 'foo', value });\nconst createBar = (value: string): BarId => ({ type: 'bar', value });\n\nlet foo = createFoo('sample')\nlet bar = createBar('sample');\n\nfoo = bar; // Error\nfoo = foo; // Okay\n```\n\n* Advantages\n  - No need for any type assertions \n* Disadvantage\n  - The structure `{type,value}` might not be desireable and need server serialization support\n\n## Using Enums\n[Enums in TypeScript](../enums.md) offer a certain level of nominal typing. Two enum types aren't equal if they differ by name. We can use this fact to provide nominal typing for types that are otherwise structurally compatible.\n\nThe workaround involves:\n* Creating a *brand* enum.\n* Creating the type as an *intersection* (`&`) of the brand enum + the actual structure.\n\nThis is demonstrated below where the structure of the types is just a string:\n\n```ts\n// FOO\nenum FooIdBrand { _ = \"\" };\ntype FooId = FooIdBrand & string;\n\n// BAR\nenum BarIdBrand  { _ = \"\" };\ntype BarId = BarIdBrand & string;\n\n/**\n * Usage Demo\n */\nvar fooId: FooId;\nvar barId: BarId;\n\n// Safety!\nfooId = barId; // error\nbarId = fooId; // error\n\n// Newing up\nfooId = 'foo' as FooId;\nbarId = 'bar' as BarId;\n\n// Both types are compatible with the base\nvar str: string;\nstr = fooId;\nstr = barId;\n```\n\nNote how the brand enums,  ``FooIdBrand`` and ``BarIdBrand`` above, each have single member (`_`) that maps to the empty string, as specified by ``{ _ = \"\" }``. This forces TypeScript to infer that these are string-based enums, with values of type ``string``, and not enums with values of type ``number``.  This is necessary because TypeScript infers an empty enum (``{}``) to be a numeric enum, and as of TypeScript 3.6.2 the intersection of a numeric ``enum`` and ``string`` is ``never``.\n\n## Using Interfaces\n\nBecause `numbers` are type compatible with `enum`s the previous technique cannot be used for them. Instead we can use interfaces to break the structural compatibility. This method is still used by the TypeScript compiler team, so worth mentioning. Using `_` prefix and a `Brand` suffix is a convention I strongly recommend (and [the one followed by the TypeScript team](https://github.com/Microsoft/TypeScript/blob/7b48a182c05ea4dea81bab73ecbbe9e013a79e99/src/compiler/types.ts#L693-L698)).\n\nThe workaround involves the following:\n* adding an unused property on a type to break structural compatibility.\n* using a type assertion when needing to new up or cast down.\n\nThis is demonstrated below:\n\n```ts\n// FOO\ninterface FooId extends String {\n    _fooIdBrand: string; // To prevent type errors\n}\n\n// BAR\ninterface BarId extends String {\n    _barIdBrand: string; // To prevent type errors\n}\n\n/**\n * Usage Demo\n */\nvar fooId: FooId;\nvar barId: BarId;\n\n// Safety!\nfooId = barId; // error\nbarId = fooId; // error\nfooId = <FooId>barId; // error\nbarId = <BarId>fooId; // error\n\n// Newing up\nfooId = 'foo' as any;\nbarId = 'bar' as any;\n\n// If you need the base string\nvar str: string;\nstr = fooId as any;\nstr = barId as any;\n```\n"
  },
  {
    "path": "docs/tips/outFile.md",
    "content": "# `--outFile` is BAD {#outFile}\n\nIts a bad idea for you to use because of the following reasons:\n\n* Runtime Errors\n* Fast compile\n* Global scope\n* Hard to analyze\n* Hard to scale\n* `_references`\n* Code reuse\n* Multiple Targets\n* Isolated Compile\n\n## Runtime Errors\n\nIf your code depends on any form of js ordering you will get random errors at runtime.\n\n* **class inheritance can break at runtime.**\n\nConsider `foo.ts`: \n```ts\nclass Foo {\n    \n}\n```\n\nand a `bar.ts`:\n```ts\nclass Bar extends Foo {\n    \n}\n```\n\nIf you fail to compile it in correct order e.g. perhaps alphabetically `tsc bar.ts foo.ts` the code will compile fine but error at runtime with `ReferenceError`. \n\n* **module splitting can fail at runtime.**\n\nConsider `foo.ts`: \n```ts\nmodule App {\n    export var foo = 123;\n}\n```\nAnd `bar.ts`: \n```ts\nmodule App {\n    export var bar = foo + 456;\n}\n```\n\nIf you fail to compile it in correct order e.g. perhaps alphabetically `tsc bar.ts foo.ts` the code will compile fine but  *silently* fail at runtime with `bar` set to `NaN`. \n\n## Fast compile\nIf you use `--out` then single `.ts` files cannot be codegened into single `.js` files in isolation without unnecessary hacks. `--out` essentially forces a slower incremental build.\n\nAlso source maps are positionally sensitive and run-length encoded so most of the map has to be rebuilt on a recompile if you use source maps (which you should!). At high-10s to 100s kloc combined it’s going to get slow.\n\n## Global Scope\nSure you can use name spaces but its still on `window` if you run it in the browser. Namespaces are just an unnecessary workaround. Also `/// <reference` comments introduce a global context in *your code* that can get hard to maintain.\n\nAlso if your company has several teams working independently and then someone decides to try integrating two independently written apps there is a high likelihood of a name conflict.\n\n## Hard to analyze\nWe wish to provide more code analysis tools. These will be easier if you provide us with the dependency chain (implicitly there on a silver platter using external modules). \n\nAlso its not just the *dev tools* that have a hard time making sense of the code. The next human needs to understand a lot of the code base before they start to understand where stuff is actually imported from. Using internal modules also makes code difficult to review in isolation e.g. on github.\n\n## Hard to scale\nReally just a result of random runtime errors + slower and slower compile times + difficulty in understanding someone else's code.\n\n## `_references.ts`\nIsn't supported by `tsconfig.json` : https://github.com/Microsoft/TypeScript/issues/2472#issuecomment-85330803 You'll have to manually sort the  `files` array. \n\n## Code reuse\nIf you want to reuse a portion of your code in another project, with all that *implicit* dependency management, it will be difficult to port it over without potential runtime errors. \n\n## Multiple Targets\nAlso if you decide to reuse your browser code in something like nodejs (e.g. for *testing* APIs) you are going to need to port it over to a module system or come up with ugly hacks to make the nodejs `global` your new global scope (i.e. `window`).\n\n## Isolated Compile\nFiles cannot be compiled in isolation. E.g. consider `a.ts`: \n```ts\nmodule M {\n  var s = t;\n}\n```\nWill have different output depending upon whether there is a `b.ts` of the form: \n```ts\nmodule M {\n  export var t = 5;\n}\n```\nor \n```ts\nvar t = 5;\n```\nSo `a.ts` [cannot be compiled in isolation](https://github.com/Microsoft/TypeScript/issues/2715).\n\n## Summary\n`--out` is really the job of some build tool. And even such a build tool can benefit from the dependency mentions provided by external modules. So we recommend you use external modules and then let the build tool create a single `.js` for you if you so desire.\n\nhttps://twitter.com/nycdotnet/status/613705850574778368 \n\n![The Bas Signal](https://pbs.twimg.com/media/CIRSOBmWsAQdzvP.jpg)\n"
  },
  {
    "path": "docs/tips/propertySetters.md",
    "content": "## Limit usage of property setters\n\nPrefer explicit set/get functions (e.g. `setBar` and `getBar` functions) over setters/getters.\n\nConsider the following code:\n\n```ts\nfoo.bar = {\n    a: 123,\n    b: 456\n};\n```\n\nIn the presence of setter/getters:\n\n```ts\nclass Foo {\n    a: number;\n    b: number;\n    set bar(value:{a:number,b:number}) {\n        this.a = value.a;\n        this.b = value.b;\n    }\n}\nlet foo = new Foo();\n```\n\nThis is not a *good* use of property setters. The person reading the first code sample has no context about all the things that will change. Whereas someone calling `foo.setBar(value)` might have an idea that something might change on `foo`.\n\n> Bonus points: Find references works better if you have different functions. In TypeScript tools if you find references for a getter or a setter you get *both* whereas with explicit function calls you only get references to the relevant function.\n"
  },
  {
    "path": "docs/tips/singleton.md",
    "content": "# Singleton Pattern\n\nThe conventional singleton pattern is really something that is used to overcome the fact that all code must be in a `class`.\n\n```ts\nclass Singleton {\n    private static instance: Singleton;\n    private constructor() {\n        // do something construct...\n    }\n    static getInstance() {\n        if (!Singleton.instance) {\n            Singleton.instance = new Singleton();\n            // ... any one time initialization goes here ...\n        }\n        return Singleton.instance;\n    }\n    someMethod() { }\n}\n\nlet something = new Singleton() // Error: constructor of 'Singleton' is private.\n\nlet instance = Singleton.getInstance() // do something with the instance...\n```\n\nHowever, if you don't want lazy initialization you can instead just use a `namespace`: \n\n```ts\nnamespace Singleton {\n    // ... any one time initialization goes here ...\n    export function someMethod() { }\n}\n// Usage\nSingleton.someMethod();\n```\n\n> Warning : Singleton is just a fancy name for [global](http://stackoverflow.com/a/142450/390330)\n\nFor most projects `namespace` can additionally be replaced by a *module*.\n\n```ts\n// someFile.ts\n// ... any one time initialization goes here ...\nexport function someMethod() { }\n\n// Usage\nimport {someMethod} from \"./someFile\";\n```\n\n\n"
  },
  {
    "path": "docs/tips/statefulFunctions.md",
    "content": "## Stateful Functions\nA common feature in other programming languages is usage of the `static` keyword to increase the *lifetime* (not *scope*) of a function variable to live beyond function invocations. Here is a `C` sample that achieves this:\n\n```c\nvoid called() {\n    static count = 0;\n    count++;\n    printf(\"Called : %d\", count);\n}\n\nint main () {\n    called(); // Called : 1\n    called(); // Called : 2\n    return 0;\n}\n```\n\nSince JavaScript (or TypeScript) doesn't have function statics you can achieve the same thing using various abstractions that wrap over a local variable e.g. using a `class` :\n\n```ts\nconst {called} = new class {\n    count = 0;\n    called = () => {\n        this.count++;\n        console.log(`Called : ${this.count}`);\n    }\n};\n\ncalled(); // Called : 1\ncalled(); // Called : 2\n```\n\n> C++ developers also try and achieve this using a pattern they call `functor` (a class that overrides the operator `()`).\n"
  },
  {
    "path": "docs/tips/staticConstructor.md",
    "content": "# Static Constructors in TypeScript\n\nTypeScript `class` (like JavaScript `class`) cannot have a static constructor. However, you can get the same effect quite easily by just calling it yourself: \n\n```ts\nclass MyClass {\n    static initialize() {\n        // Initialization\n    }\n}\nMyClass.initialize();\n```\n"
  },
  {
    "path": "docs/tips/stringEnums.md",
    "content": "## String enums\n\nSometimes you need a collection of strings collected under a common key. Prior to TypeScript 2.4, TypeScript only supported number-based enums. If using versions prior to 2.4, a work-around is to use [string literal types to create string based enums by combining with union types](../types/literal-types.md).\n"
  },
  {
    "path": "docs/tips/typeInstantiation.md",
    "content": "## Type Instantiation for Generics\n\nSay you have something that has a generic parameter e.g. a class `Foo`:\n\n```ts\nclass Foo<T>{\n\tfoo: T;\n}\n```\n\nYou want to create a specialized version for it for a particular type. The pattern is to copy the item into a new variable and give it the type annotation with the generics replaced with concrete types. E.g. if you want a class `Foo<number>`:\n\n```ts\nclass Foo<T>{\n\tfoo: T;\n}\nlet FooNumber = Foo as { new ():Foo<number> }; // ref 1\n```\nIn `ref 1` you are saying that `FooNumber` is the same as `Foo` but just treat it as something that when called with the `new` operator gives an instance of `Foo<Number>`.\n\n### Inheritance\nThe Type assertion pattern is unsafe in that it trusts you to do the right thing. A common pattern in other languages *for classes* is to just use inheritance :\n\n```ts\nclass FooNumber extends Foo<number>{}\n```\n\nOne word of caution here: if you use decorators on the base class then the inherited class might not have the same behavior as the base class (it is no longer wrapped by the decorator).\n\nOf course if you are not specializing classes you still have to come up with a coercion / assertion pattern that works and hence we showed the general assertion pattern first, e.g.:\n\n```ts\nfunction id<T>(x: T) { return x; }\nconst idNum = id as {(x:number):number};\n```\n\n> Inspired by this [stackoverflow question](http://stackoverflow.com/a/34864705/390330)\n"
  },
  {
    "path": "docs/tips/typed-event.md",
    "content": "## Typesafe Event Emitter\n\nConventionally in Node.js and traditional JavaScript you have a single event emitter. This event emitter internally tracks listener for different event types e.g. \n\n```ts\nconst emitter = new EventEmitter();\n// Emit: \nemitter.emit('foo', foo);\nemitter.emit('bar', bar);\n// Listen: \nemitter.on('foo', (foo)=>console.log(foo));\nemitter.on('bar', (bar)=>console.log(bar));\n```\nEssentially `EventEmitter` internally stores data in the form of mapped arrays: \n```ts\n{foo: [fooListeners], bar: [barListeners]}\n```\nInstead, for the sake of *event* type safety, you can create an emitter *per* event type:\n```ts\nconst onFoo = new TypedEvent<Foo>();\nconst onBar = new TypedEvent<Bar>();\n\n// Emit: \nonFoo.emit(foo);\nonBar.emit(bar);\n// Listen: \nonFoo.on((foo)=>console.log(foo));\nonBar.on((bar)=>console.log(bar));\n```\n\nThis has the following advantages: \n* The types of events are easily discoverable as variables.\n* The event emitter variables are easily refactored independently.\n* Type safety for event data structures.\n\n### Reference TypedEvent\n```ts\nexport interface Listener<T> {\n  (event: T): any;\n}\n\nexport interface Disposable {\n  dispose();\n}\n\n/** passes through events as they happen. You will not get events from before you start listening */\nexport class TypedEvent<T> {\n  private listeners: Listener<T>[] = [];\n  private listenersOncer: Listener<T>[] = [];\n\n  on = (listener: Listener<T>): Disposable => {\n    this.listeners.push(listener);\n    return {\n      dispose: () => this.off(listener)\n    };\n  }\n\n  once = (listener: Listener<T>): void => {\n    this.listenersOncer.push(listener);\n  }\n\n  off = (listener: Listener<T>) => {\n    var callbackIndex = this.listeners.indexOf(listener);\n    if (callbackIndex > -1) this.listeners.splice(callbackIndex, 1);\n  }\n\n  emit = (event: T) => {\n    /** Update any general listeners */\n    this.listeners.forEach((listener) => listener(event));\n\n    /** Clear the `once` queue */\n    if (this.listenersOncer.length > 0) {\n      const toCall = this.listenersOncer;\n      this.listenersOncer = [];\n      toCall.forEach((listener) => listener(event));\n    }\n  }\n\n  pipe = (te: TypedEvent<T>): Disposable => {\n    return this.on((e) => te.emit(e));\n  }\n}\n```\n"
  },
  {
    "path": "docs/tools/changelog.md",
    "content": "## Changelog \n> Reading a markdown file with the progress in the project is easier than reading a commit log.\n\nAutomatic changelog generation from commit messages is a fairly common pattern nowadays. There is a project called [conventional-changelog](https://github.com/conventional-changelog/conventional-changelog) that generates a changelog from commit messages that follow a *convention*. \n\n### Commit message convention\nThe most common convention is the *angular* commit messages convention which is [detailed here](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#-git-commit-guidelines).\n\n### Setup\n* Install: \n\n```bash\nnpm install standard-version -D\n```\n\n* Add a `script` target to your `package.json`: \n\n```js\n{\n  \"scripts\": {\n    \"release\": \"standard-version\"\n  }\n}\n```\n\n* Optionally : To automatically push the new *git commit and tag* plus publish to npm add a `postrelease` script: \n\n```js\n{\n  \"scripts\": {\n    \"release\": \"standard-version\",\n    \"postrelease\": \"git push --follow-tags origin master && npm publish\"\n  }\n}\n```\n\n### Releasing \n\nSimply run: \n\n```bash\nnpm run release\n```\n\nBased on the commit messages `major` | `minor` | `patch` is automatically determined. To *explicitly* specify a version you can specify `--release-as` e.g.: \n\n```bash\nnpm run release -- --release-as minor\n```\n"
  },
  {
    "path": "docs/tools/eslint.md",
    "content": "# ESLint\n\nESLint existed to lint JavaScript, but now it is also becoming the defacto linter for [TypeScript](https://github.com/Microsoft/TypeScript/issues/29288), thanks to the [collaboration](https://eslint.org/blog/2019/01/future-typescript-eslint) between the two teams.\n\n## Install\n\nTo setup ESLint for TypeScript you need the following packages:\n\n```sh\nnpm i eslint eslint-plugin-react @typescript-eslint/parser @typescript-eslint/eslint-plugin\n```\n\n> TIP: eslint calls packages that contain lint rules as \"plugin\"\n\n* eslint : Core eslint \n* eslint-plugin-react : For react rules provided by eslint. [Supported rules list](https://github.com/yannickcr/eslint-plugin-react#list-of-supported-rules)\n* @typescript-eslint/parse : To allow eslint to understand ts / tsx files \n* @typescript-eslint/eslint-plugin : For TypeScript rules. [Supported rules list](https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/eslint-plugin#supported-rules)\n\n> As you can see there are two eslint packages (for use with js or ts) and two @typescript-eslint packages (for use with ts). So the overhead for TypeScript is not *that much*.\n\n## Configure \nCreate `.eslintrc.js`: \n\n```js\nmodule.exports = {\n  parser: '@typescript-eslint/parser',\n  parserOptions: {\n    project: './tsconfig.json',\n  },\n  plugins: ['@typescript-eslint'],\n  extends: [\n    'plugin:react/recommended',\n    'plugin:@typescript-eslint/recommended',\n  ],\n  rules:  {\n    // Overwrite rules specified from the extended configs e.g. \n    // \"@typescript-eslint/explicit-function-return-type\": \"off\",\n  }\n}\n```\n\n## Run\n\nIn your `package.json` add to `scripts`: \n\n```json\n{\n  \"scripts\": {\n    \"lint\": \"eslint \\\"src/**\\\"\"\n  }\n}\n```\n\nNow you can `npm run lint` to validate.\n\n## Configure VSCode \n\n* Install extension https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint\n* Add to `settings.json`:\n```js\n\"eslint.validate\":  [\n  \"javascript\",\n  \"javascriptreact\",\n  {\"language\":  \"typescript\",  \"autoFix\":  true  },\n  {\"language\":  \"typescriptreact\",  \"autoFix\":  true  }\n],\n```\n"
  },
  {
    "path": "docs/tools/husky.md",
    "content": "# Husky \n\n> Husky can prevent bad commits, pushes and more 🐶!\n\nIf you want to run some JavaScript / TypeScript code before a commit takes place, husky is the tool for that. \n\nFor example, you can use husky to make sure files are formatted by prettier automatically so you don't have to worry about manually formatting files ever again and focus on the objective of the code instead. Here is the setup: \n\n* `npm install husky -D`\n* Add `scripts` to `package.json`: \n\n```\n    \"precommit\": \"npm run prettier:write\",\n```\n\nNow whenever you commit code and there are any formatting changes that need to be made, you'd get them as a *modified* file in your git log. You can now \n\n* If you have pushed your code already, simply commit them with a comment `pretty`.\n* If you haven't pushed your code, amend your last commit and look like a superhero.\n"
  },
  {
    "path": "docs/tools/intro.md",
    "content": "# Tools\nHere are some great tools that I recommend you use or at least try in your TypeScript projects. \n"
  },
  {
    "path": "docs/tools/prettier.md",
    "content": "# Prettier \n\nPrettier is a great tool by facebook that makes code formatting so much easier that it's worth mentioning. Setting up with TypeScript using our recommended project setup (aka everything in `src` folder) is super easy: \n\n## Setup \n\n* `npm install prettier -D` \n* Add `scripts` to `package.json`: \n\n```\n    \"prettier:base\": \"prettier --parser typescript --single-quote\",\n    \"prettier:check\": \"npm run prettier:base -- --list-different \\\"src/**/*.{ts,tsx}\\\"\",\n    \"prettier:write\": \"npm run prettier:base -- --write \\\"src/**/*.{ts,tsx}\\\"\"\n```\n\n## Usage \nOn your build server: \n* `npm run prettier:check` \n\nDuring dev (or pre commit hook): \n* `npm run prettier:write`\n"
  },
  {
    "path": "docs/types/@types.md",
    "content": "# `@types`\n\n[Definitely Typed](https://github.com/DefinitelyTyped/DefinitelyTyped) is definitely one of TypeScript's greatest strengths. The community has effectively gone ahead and **documented** the nature of nearly 90% of the top JavaScript projects out there.\n\nThis means that you can use these projects in a very interactive and exploratory manner, no need to have the docs open in a separate window and making sure you don't make a typo.\n\n## Using `@types`\n\nInstallation is fairly simple as it just works on top of `npm`. So as an example you can install type definitions for `jquery` simply as:\n\n```\nnpm install @types/jquery --save-dev\n```\n\n`@types` supports both *global* and *module* type definitions.\n\n\n### Global `@types`\n\nBy default any definitions that support global consumption are included automatically. E.g. for `jquery` you should be able to just start using `$` *globally* in your project.\n\nHowever, for *libraries*  (like `jquery`) I generally recommend using *modules*:\n\n### Module `@types`\n\nAfter installation, no special configuration is required really. You just use it like a module e.g.:\n\n```ts\nimport * as $ from \"jquery\";\n\n// Use $ at will in this module :)\n```\n\n## Controlling Globals\n\nAs can be seen, having a definition that allows global leak-in automatically can be a problem for some teams. So you can choose to *explicitly* only bring in the types that make sense using the `tsconfig.json` `compilerOptions.types` e.g.:\n\n```json\n{\n    \"compilerOptions\": {\n        \"types\" : [\n            \"jquery\"\n        ]\n    }\n}\n```\n\nThe above shows a sample where only `jquery` will be allowed to be used. Even if the person installs another definition like `npm install @types/node` its globals (e.g. [`process`](https://nodejs.org/api/process.html)) will not leak into your code until you add them to the `tsconfig.json` types option.\n"
  },
  {
    "path": "docs/types/advanced.md",
    "content": "\n\n\n\n# Functions\n\n## Optional\nThe `?` annotation can be used before a function argument or member of an interface to denote that a member is optional. That is to say that you can provide it if you want (and it will be type checked), but if it is ommited its *okay*. This is shown in the following example:\n\n## Specialized Parameters\n\n## Function Overloads\nThe JavaScript runtime does not have runtime support for function overloading. There can be only a single function body for any given name in scope. However, people do support function overloading by utilizing the highly dynamic nature of JavaScript e.g. a getter and a setter:\n\n```ts\nvar _value;\nfunction getOrSet(value) {\n    if (value === undefined) {\n        return _value;\n    } else {\n        _value = value;\n    }\n}\n\ngetOrSet(1); // set : 1\nconsole.log(getOrSet()); // get : 1\n```\n\nSuch implementation can be captured by the TypeScript's type system by providing function signatures before the function implementation:\n\n```ts\nvar _value;\nfunction getOrSet(): number;\nfunction getOrSet(value: number);\nfunction getOrSet(value?: number) {\n    if (value === undefined) {\n        return _value;\n    } else {\n        _value = value;\n    }\n}\n\ngetOrSet(1); // set : 1\nconsole.log(getOrSet()); // get : 1\n```\n\nNote that when you define function overloads this way, *the last signature is actually not callable*. You have to provide it however, to help the implementer of the function be aware of the consequences of his overload signatures. For example, in the following example the function with the signature `function callMe(v1?: any, v2?: any): any` is not open to public use:\n\n```ts\nfunction callMe(): number;\nfunction callMe(v1: number);\nfunction callMe(v1: string, v2: number);\nfunction callMe(v1?: any, v2?: any): any {\n    // Implementation body goes here\n}\n\n// Allowed calls\ncallMe();\ncallMe(1);\ncallMe('jenny', 5309);\n\n// COMPILER ERROR: invalid calls\ncallMe('jenny');\ncallMe('jenny', '5309');\n```\n\nTIP: Note that there is a slight overlap between union types and function overloading. If two function signatures only differ by a single parameter having different types just use a union type for that parameter instead of creating an overload signature.\n\n\n# Interfaces\n\nInterfaces have a lot of power in TypeScript. This is because they are designed to capture all the complexity of\n\n\n\n\n# Ambient Declarations\n\nWe previously had a brief look at ambient declarations in the section *why typescript?*. One of the core design goals of TypeScript is to allow easy consumption of existing JavaScript libraries. You can declare the type information for existing JavaScript using *ambient declarations*. You declare ambient stuff using the `declare` keyword. In fact this is how a bunch of stuff available by default in a browser environment (e.g `window`, `document` etc) is declared in a file called `lib.d.ts`\n\n\nNote: You can find type definitions for nearly 90% of the most popular JavaScript libraries at [DefinitelyTyped](https://github.com/borisyankov/DefinitelyTyped) with contributions from [lots of  developers](https://github.com/borisyankov/DefinitelyTyped/graphs/contributors).\n\n\n\n### lib.d.ts\n\n# Interfaces\n\n\n\n### Interfaces for primitive types\n\n### Interface for array\n\n## Type Alias\n\n## Union Types\nneeded for configuration objects\n\n## Type Inference\nIt tries to *infer* as much as it can *so that you don't need to explicitly type* your code.\n\n## Function Signatures\n\nSpecialized\n\n## Type Assertion\n\nIf A is a subtype of B or B is a subtype of A.\n\n\n\n\n\n\n\n\n[more on interfaces]\nStructural so more information is okay, but less information is an error. Duck typing is baked deep into the language design.\nOpen Ended\nType Compatibility\n"
  },
  {
    "path": "docs/types/ambient/d.ts.md",
    "content": "### Declaration file\nYou can tell TypeScript that you are trying to describe code that exists elsewhere (e.g. written in JavaScript/CoffeeScript/The runtime environment like the browser or Node.js) using the `declare` keyword. As a quick example:\n\n```ts\nfoo = 123; // Error: `foo` is not defined\n```\nvs.\n```ts\ndeclare var foo: any;\nfoo = 123; // allowed\n```\n\nYou have the option of putting these declarations in a `.ts` file or in a `.d.ts` file. We highly recommend that in your real world projects you use a separate `.d.ts` (start with one called something like `global.d.ts` or `vendor.d.ts`).\n\nIf a file has the extension `.d.ts` then each root level definition must have the `declare` keyword prefixed to it. This helps make it clear to the author that there will be *no code emitted by TypeScript*. The author needs to ensure that the declared item will exist at runtime.\n\n> * Ambient declarations is a promise that you are making with the compiler. If these do not exist at runtime and you try to use them, things will break without warning.\n* Ambient declarations are like docs. If the source changes the docs need to be kept updated. So you might have new behaviours that work at runtime but no one's updated the ambient declaration and hence you get compiler errors.\n"
  },
  {
    "path": "docs/types/ambient/intro.md",
    "content": "## Ambient Declarations\n\nAs we mentioned in [why TypeScript](../../why-typescript.md):\n\n> A major design goal of TypeScript was to make it possible for you to safely and easily use existing JavaScript libraries in TypeScript. TypeScript does this by means of *declaration*.\n\nAmbient declarations allow you to *safely use existing popular JavaScript libraries* and *incrementally migrate your JavaScript/CoffeeScript/Other-Compile-To-Js-Language project to TypeScript*.\n\nStudying patterns in ambient declarations for *third party JavaScript code* is good practice for annotating *your* TypeScript code base as well. This is why we present it so early on.\n"
  },
  {
    "path": "docs/types/ambient/variables.md",
    "content": "### Variables\nFor example to tell TypeScript about the [`process` variable](https://nodejs.org/api/process.html) you *can* do:\n\n```ts\ndeclare var process: any;\n```\n\n> You don't *need* to do this for `process` as there is already a [community maintained `node.d.ts`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/index.d.ts).\n\nThis allows you to use the `process` variable without TypeScript complaining:\n\n```ts\nprocess.exit();\n```\n\nWe recommend using an interface wherever possible e.g.:\n\n```ts\ninterface Process {\n    exit(code?: number): void;\n}\ndeclare var process: Process;\n```\n\nThis allows other people to *extend* the nature of these global variables while still telling TypeScript about such modifications. E.g. consider the following case where we add an `exitWithLogging` function to process for our amusement:\n\n```ts\ninterface Process {\n    exitWithLogging(code?: number): void;\n}\nprocess.exitWithLogging = function() {\n    console.log(\"exiting\");\n    process.exit.apply(process, arguments);\n};\n```\n\nLet's look at interfaces in a bit more detail next.\n"
  },
  {
    "path": "docs/types/callable.md",
    "content": "## Callable\nYou can annotate callables as a part of a type or an interface as follows\n\n```ts\ninterface ReturnString {\n  (): string\n}\n```\nAn instance of such an interface would be a function that returns a string e.g.\n\n```ts\ndeclare const foo: ReturnString;\nconst bar = foo(); // bar is inferred as a string\n```\n\n### Obvious examples\nOf course such a *callable* annotation can also specify any arguments / optional arguments / rest arguments as needed. e.g. here is a complex example:\n\n```ts\ninterface Complex {\n  (foo: string, bar?: number, ...others: boolean[]): number;\n}\n```\n\nAn interface can provide multiple callable annotations to specify function overloading. For example:\n\n```ts\ninterface Overloaded {\n    (foo: string): string\n    (foo: number): number\n}\n\n// example implementation\nfunction stringOrNumber(foo: number): number;\nfunction stringOrNumber(foo: string): string;\nfunction stringOrNumber(foo: any): any {\n    if (typeof foo === 'number') {\n        return foo * foo;\n    } else if (typeof foo === 'string') {\n        return `hello ${foo}`;\n    }\n}\n\nconst overloaded: Overloaded = stringOrNumber;\n\n// example usage\nconst str = overloaded(''); // type of `str` is inferred as `string`\nconst num = overloaded(123); // type of `num` is inferred as `number`\n```\n\nOf course, like the body of *any* interface, you can use the body of a callable interface as a type annotation for a variable. For example:\n\n```ts\nconst overloaded: {\n  (foo: string): string\n  (foo: number): number\n} = (foo: any) => foo;\n```\n\n### Arrow Syntax\nTo make it easy to specify callable signatures, TypeScript also allows simple arrow type annotations. For example, a function that takes a `number` and returns a `string` can be annotated as:\n\n```ts\nconst simple: (foo: number) => string\n    = (foo) => foo.toString();\n```\n\n> Only limitation of the arrow syntax: You can't specify overloads. For overloads you must use the full bodied `{ (someArgs): someReturn }` syntax.\n\n### Newable\n\nNewable is just a special type of *callable* type annotation with the prefix `new`. It simply means that you need to *invoke* with `new` e.g.\n\n```ts\ninterface CallMeWithNewToGetString {\n  new(): string\n}\n// Usage\ndeclare const Foo: CallMeWithNewToGetString;\nconst bar = new Foo(); // bar is inferred to be of type string\n```\n"
  },
  {
    "path": "docs/types/discriminated-unions.md",
    "content": "### Discriminated Union\n\nIf you have a class with a [*literal member*](./literal-types.md) then you can use that property to discriminate between union members.\n\nAs an example consider the union of a `Square` and `Rectangle`, here we have a member `kind` that exists on both union members and is of a particular *literal type*:\n\n```ts\ninterface Square {\n    kind: \"square\";\n    size: number;\n}\n\ninterface Rectangle {\n    kind: \"rectangle\";\n    width: number;\n    height: number;\n}\ntype Shape = Square | Rectangle;\n```\n\nIf you use a type guard style check (`==`, `===`, `!=`, `!==`) or `switch` on the *discriminant property* (here `kind`) TypeScript will realize that the object must be of the type that has that specific literal and do a type narrowing for you :)\n\n```ts\nfunction area(s: Shape) {\n    if (s.kind === \"square\") {\n        // Now TypeScript *knows* that `s` must be a square ;)\n        // So you can use its members safely :)\n        return s.size * s.size;\n    }\n    else {\n        // Wasn't a square? So TypeScript will figure out that it must be a Rectangle ;)\n        // So you can use its members safely :)\n        return s.width * s.height;\n    }\n}\n```\n\n### Exhaustive Checks\nQuite commonly you want to make sure that all members of a union have some code(action) against them.\n\n```ts\ninterface Square {\n    kind: \"square\";\n    size: number;\n}\n\ninterface Rectangle {\n    kind: \"rectangle\";\n    width: number;\n    height: number;\n}\n\n// Someone just added this new `Circle` Type\n// We would like to let TypeScript give an error at any place that *needs* to cater for this\ninterface Circle {\n    kind: \"circle\";\n    radius: number;\n}\n\ntype Shape = Square | Rectangle | Circle;\n```\n\nAs an example of where stuff goes bad:\n\n```ts\nfunction area(s: Shape) {\n    if (s.kind === \"square\") {\n        return s.size * s.size;\n    }\n    else if (s.kind === \"rectangle\") {\n        return s.width * s.height;\n    }\n    // Would it be great if you could get TypeScript to give you an error?\n}\n```\n\nYou can do that by simply adding a fall through and making sure that the inferred type in that block is compatible with the `never` type. For example if you add the exhaustive check you get a nice error:\n\n```ts\nfunction area(s: Shape) {\n    if (s.kind === \"square\") {\n        return s.size * s.size;\n    }\n    else if (s.kind === \"rectangle\") {\n        return s.width * s.height;\n    }\n    else {\n        // ERROR : `Circle` is not assignable to `never`\n        const _exhaustiveCheck: never = s;\n    }\n}\n```\n\nThat forces you to handle this new case : \n\n```ts\nfunction area(s: Shape) {\n    if (s.kind === \"square\") {\n        return s.size * s.size;\n    }\n    else if (s.kind === \"rectangle\") {\n        return s.width * s.height;\n    }\n    else if (s.kind === \"circle\") {\n        return Math.PI * (s.radius **2);\n    }\n    else {\n        // Okay once more\n        const _exhaustiveCheck: never = s;\n    }\n}\n```\n\n\n### Switch\nTIP: of course you can also do it in a `switch` statement:\n\n```ts\nfunction area(s: Shape) {\n    switch (s.kind) {\n        case \"square\": return s.size * s.size;\n        case \"rectangle\": return s.width * s.height;\n        case \"circle\": return Math.PI * s.radius * s.radius;\n        default: const _exhaustiveCheck: never = s;\n    }\n}\n```\n\n[references-discriminated-union]:https://github.com/Microsoft/TypeScript/pull/9163\n\n### strictNullChecks\n\nIf using *strictNullChecks* and doing exhaustive checks, TypeScript might complain \"not all code paths return a value\". You can silence that by simply returning the `_exhaustiveCheck` variable (of type `never`). So:\n\n```ts\nfunction area(s: Shape) {\n    switch (s.kind) {\n        case \"square\": return s.size * s.size;\n        case \"rectangle\": return s.width * s.height;\n        case \"circle\": return Math.PI * s.radius * s.radius;\n        default:\n          const _exhaustiveCheck: never = s;\n          return _exhaustiveCheck;\n    }\n}\n```\n\n### Throw in exhaustive checks\nYou can write a function that takes a `never` (and therefore can only be called with a variable that is inferred as `never`) and then throws an error if its body ever executes: \n\n```ts\nfunction assertNever(x:never): never {\n    throw new Error('Unexpected value. Should have been never.');\n}\n```\n\nExample use with the area function: \n\n```ts\ninterface Square {\n    kind: \"square\";\n    size: number;\n}\ninterface Rectangle {\n    kind: \"rectangle\";\n    width: number;\n    height: number;\n}\ntype Shape = Square | Rectangle;\n\nfunction area(s: Shape) {\n    switch (s.kind) {\n        case \"square\": return s.size * s.size;\n        case \"rectangle\": return s.width * s.height;\n\t\t// If a new case is added at compile time you will get a compile error\n\t\t// If a new value appears at runtime you will get a runtime error\n        default: return assertNever(s);\n    }\n}\n```\n\n### Retrospective Versioning\nSay you have a data structure of the form: \n\n```ts\ntype DTO = {\n  name: string\n}\n```\nAnd after you have a bunch of `DTO`s you realize that `name` was a poor choice. You can add versioning retrospectively by creating a new *union* with *literal number* (or string if you want) of DTO. Mark the version 0 as `undefined` and if you have *strictNullChecks* enabled it will just work out: \n\n```ts\ntype DTO = \n| { \n   version: undefined, // version 0\n   name: string,\n }\n| {\n   version: 1,\n   firstName: string,\n   lastName: string, \n}\n// Even later \n| {\n    version: 2,\n    firstName: string,\n    middleName: string,\n    lastName: string, \n} \n// So on\n```\n\n Example usage of such a DTO:\n\n```ts\nfunction printDTO(dto:DTO) {\n  if (dto.version == null) {\n      console.log(dto.name);\n  } else if (dto.version == 1) {\n      console.log(dto.firstName,dto.lastName);\n  } else if (dto.version == 2) {\n      console.log(dto.firstName, dto.middleName, dto.lastName);\n  } else {\n      const _exhaustiveCheck: never = dto;\n  }\n}\n```\n\n### Redux\n\nA popular library that makes use of this is redux.\n\nHere is the [*gist of redux*](https://github.com/reactjs/redux#the-gist) with TypeScript type annotations added:\n\n```ts\nimport { createStore } from 'redux'\n\ntype Action\n  = {\n    type: 'INCREMENT'\n  }\n  | {\n    type: 'DECREMENT'\n  }\n\n/**\n * This is a reducer, a pure function with (state, action) => state signature.\n * It describes how an action transforms the state into the next state.\n *\n * The shape of the state is up to you: it can be a primitive, an array, an object,\n * or even an Immutable.js data structure. The only important part is that you should\n * not mutate the state object, but return a new object if the state changes.\n *\n * In this example, we use a `switch` statement and strings, but you can use a helper that\n * follows a different convention (such as function maps) if it makes sense for your\n * project.\n */\nfunction counter(state = 0, action: Action) {\n  switch (action.type) {\n  case 'INCREMENT':\n    return state + 1\n  case 'DECREMENT':\n    return state - 1\n  default:\n    return state\n  }\n}\n\n// Create a Redux store holding the state of your app.\n// Its API is { subscribe, dispatch, getState }.\nlet store = createStore(counter)\n\n// You can use subscribe() to update the UI in response to state changes.\n// Normally you'd use a view binding library (e.g. React Redux) rather than subscribe() directly.\n// However, it can also be handy to persist the current state in the localStorage.\n\nstore.subscribe(() =>\n  console.log(store.getState())\n)\n\n// The only way to mutate the internal state is to dispatch an action.\n// The actions can be serialized, logged or stored and later replayed.\nstore.dispatch({ type: 'INCREMENT' })\n// 1\nstore.dispatch({ type: 'INCREMENT' })\n// 2\nstore.dispatch({ type: 'DECREMENT' })\n// 1\n```\n\nUsing it with TypeScript gives you safety against typo errors, increased refactor-ability and self documenting code.\n\n"
  },
  {
    "path": "docs/types/exceptions.md",
    "content": "# Exception Handling\n\nJavaScript has an `Error` class that you can use for exceptions. You throw an error with the `throw` keyword. You can catch it with a `try` / `catch` block pair e.g.\n\n```js\ntry {\n  throw new Error('Something bad happened');\n}\ncatch(e) {\n  console.log(e);\n}\n```\n\n## Error Sub Types\n\nBeyond the built in `Error` class there are a few additional built-in error classes that inherit from `Error` that the JavaScript runtime can throw:\n\n### RangeError\n\nCreates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.\n\n```js\n// Call console with too many arguments\nconsole.log.apply(console, new Array(1000000000)); // RangeError: Invalid array length\n```\n\n### ReferenceError\n\nCreates an instance representing an error that occurs when de-referencing an invalid reference. e.g.\n\n```js\n'use strict';\nconsole.log(notValidVar); // ReferenceError: notValidVar is not defined\n```\n\n### SyntaxError\n\nCreates an instance representing a syntax error that occurs while parsing code that isn't valid JavaScript.\n\n```js\n1***3; // SyntaxError: Unexpected token *\n```\n\n### TypeError\n\nCreates an instance representing an error that occurs when a variable or parameter is not of a valid type.\n\n```js\n('1.2').toPrecision(1); // TypeError: '1.2'.toPrecision is not a function\n```\n\n### URIError\n\nCreates an instance representing an error that occurs when `encodeURI()` or `decodeURI()` are passed invalid parameters.\n\n```js\ndecodeURI('%'); // URIError: URI malformed\n```\n\n## Always use `Error`\n\nBeginner JavaScript developers sometimes just throw raw strings e.g.\n\n```js\ntry {\n  throw 'Something bad happened';\n}\ncatch(e) {\n  console.log(e);\n}\n```\n\n*Don't do that*. The fundamental benefit of `Error` objects is that they automatically keep track of where they were built and originated with the `stack` property.\n\nRaw strings result in a very painful debugging experience and complicate error analysis from logs.\n\n## You don't have to `throw` an error\n\nIt is okay to pass an `Error` object around. This is conventional in Node.js callback style code which takes callbacks with the first argument as an error object.\n\n```js\nfunction myFunction (callback: (e?: Error)) {\n  doSomethingAsync(function () {\n    if (somethingWrong) {\n      callback(new Error('This is my error'))\n    } else {\n      callback();\n    }\n  });\n}\n```\n\n## Exceptional cases\n\n`Exceptions should be exceptional` is a common saying in computer science. There are a few reasons why this is true for JavaScript (and TypeScript) as well.\n\n### Unclear where it is thrown\n\nConsider the following piece of code:\n\n```js\ntry {\n  const foo = runTask1();\n  const bar = runTask2();\n}\ncatch(e) {\n  console.log('Error:', e);\n}\n```\n\nThe next developer cannot know which function might throw the error. The person reviewing the code cannot know without reading the code for task1 / task2 and other functions they might call etc.\n\n### Makes graceful handling hard\n\nYou can try to make it graceful with explicit catch around each thing that might throw:\n\n```js\ntry {\n  const foo = runTask1();\n}\ncatch(e) {\n  console.log('Error:', e);\n}\ntry {\n  const bar = runTask2();\n}\ncatch(e) {\n  console.log('Error:', e);\n}\n```\n\nBut now if you need to pass stuff from the first task to the second one the code becomes messy: (notice `foo` mutation requiring `let` + explicit need for annotating it because it cannot be inferred from the return of `runTask1`):\n\n```ts\nlet foo: number; // Notice use of `let` and explicit type annotation\ntry {\n  foo = runTask1();\n}\ncatch(e) {\n  console.log('Error:', e);\n}\ntry {\n  const bar = runTask2(foo);\n}\ncatch(e) {\n  console.log('Error:', e);\n}\n```\n\n### Not well represented in the type system\n\nConsider the function:\n\n```ts\nfunction validate(value: number) {\n  if (value < 0 || value > 100) throw new Error('Invalid value');\n}\n```\n\nUsing `Error` for such cases is a bad idea as it is not represented in the type definition for the validate function (which is `(value:number) => void`). Instead a better way to create a validate method would be:\n\n```ts\nfunction validate(value: number): {error?: string} {\n  if (value < 0 || value > 100) return {error:'Invalid value'};\n}\n```\n\nAnd now its represented in the type system.\n\n> Unless you want to handle the error in a very generic (simple / catch-all etc) way, don't *throw* an error.\n"
  },
  {
    "path": "docs/types/freshness.md",
    "content": "\n* [Freshness](#freshness)\n* [Allowing extra properties](#allowing-extra-properties)\n* [Use Case: React](#use-case-react-state)\n\n## Freshness\n\nTypeScript provides a concept of **Freshness** (also called *strict object literal checking*) to make it easier to type check object literals that would otherwise be structurally type compatible.\n\nStructural typing is *extremely convenient*. Consider the following piece of code. This allows you to *very conveniently* upgrade your JavaScript to TypeScript while still preserving a level of type safety:\n\n```ts\nfunction logName(something: { name: string }) {\n    console.log(something.name);\n}\n\nvar person = { name: 'matt', job: 'being awesome' };\nvar animal = { name: 'cow', diet: 'vegan, but has milk of own species' };\nvar random = { note: `I don't have a name property` };\n\nlogName(person); // okay\nlogName(animal); // okay\nlogName(random); // Error: property `name` is missing\n```\n\nHowever, *structural* typing has a weakness in that it allows you to misleadingly think that something accepts more data than it actually does. This is demonstrated in the following code which TypeScript will error on as shown:\n\n```ts\nfunction logName(something: { name: string }) {\n    console.log(something.name);\n}\n\nlogName({ name: 'matt' }); // okay\nlogName({ name: 'matt', job: 'being awesome' }); // Error: object literals must only specify known properties. `job` is excessive here.\n```\n\nNote that this error *only happens on object literals*. Without this error one might look at the call `logName({ name: 'matt', job: 'being awesome' })` and think that *logName* would do something useful with `job` where as in reality it will completely ignore it.\n\nAnother big use case is with interfaces that have optional members, without such object literal checking, a typo would type check just fine. This is demonstrated below:\n\n```ts\nfunction logIfHasName(something: { name?: string }) {\n    if (something.name) {\n        console.log(something.name);\n    }\n}\nvar person = { name: 'matt', job: 'being awesome' };\nvar animal = { name: 'cow', diet: 'vegan, but has milk of own species' };\n\nlogIfHasName(person); // okay\nlogIfHasName(animal); // okay\nlogIfHasName({neme: 'I just misspelled name to neme'}); // Error: object literals must only specify known properties. `neme` is excessive here.\n```\n\nThe reason why only object literals are type checked this way is because in this case additional properties *that aren't actually used* is almost always a typo or a misunderstanding of the API.\n\n### Allowing extra properties\n\nA type can include an index signature to explicitly indicate that excess properties are permitted:\n\n```ts\nvar x: { foo: number, [x: string]: unknown };\nx = { foo: 1, baz: 2 };  // Ok, `baz` matched by index signature\n```\n\n### Use Case: React State\n\n[Facebook ReactJS](https://facebook.github.io/react/) offers a nice use case for object freshness. Quite commonly in a component you call `setState` with only a few properties instead of passing in all the properties, i.e.: \n\n```ts\n// Assuming\ninterface State {\n    foo: string;\n    bar: string;\n}\n\n// You want to do: \nthis.setState({foo: \"Hello\"}); // Error: missing property bar\n\n// But because state contains both `foo` and `bar` TypeScript would force you to do: \nthis.setState({foo: \"Hello\", bar: this.state.bar});\n```\n\nUsing the idea of freshness you would mark all the members as optional and *you still get to catch typos*!: \n\n```ts\n// Assuming\ninterface State {\n    foo?: string;\n    bar?: string;\n}\n\n// You want to do: \nthis.setState({foo: \"Hello\"}); // Yay works fine!\n\n// Because of freshness it's protected against typos as well!\nthis.setState({foos: \"Hello\"}); // Error: Objects may only specify known properties\n\n// And still type checked\nthis.setState({foo: 123}); // Error: Cannot assign number to a string\n```\n"
  },
  {
    "path": "docs/types/functions.md",
    "content": "* [Parameter Annotations](#parameter-annotations)\n* [Return Type Annotation](#return-type-annotation)\n* [Optional Parameters](#optional-parameters)\n* [Overloading](#overloading)\n\n## Functions\nThe TypeScript type system pays a lot of love to functions, after all they are the core building blocks of a composable system.\n\n### Parameter annotations\nOf course you can annotate function parameters just like you can annotate other variables:\n\n```ts\n// variable annotation\nvar sampleVariable: { bar: number }\n\n// function parameter annotation\nfunction foo(sampleParameter: { bar: number }) { }\n```\n\nHere I used inline type annotations. Of course you can use interfaces etc.\n\n### Return type annotation\n\nYou can annotate the return type after the function parameter list with the same style as you use for a variable, e.g. `: Foo` in the below example:\n\n```ts\ninterface Foo {\n    foo: string;\n}\n\n// Return type annotated as `: Foo`\nfunction foo(sample: Foo): Foo {\n    return sample;\n}\n```\n\nOf course I used an `interface` here, but you are free to use other annotations e.g. inline annotations.\n\nQuite commonly you don't *need* to annotate the return type of a function as it can generally be inferred by the compiler.\n\n```ts\ninterface Foo {\n    foo: string;\n}\n\nfunction foo(sample: Foo) {\n    return sample; // inferred return type 'Foo'\n}\n```\n\nHowever, it is generally a good idea to add these annotation to help with errors e.g.:\n\n```ts\nfunction foo() {\n    return { fou: 'John Doe' }; // You might not find this misspelling of `foo` till it's too late\n}\n\nsendAsJSON(foo());\n```\n\nIf you don't plan to return anything from a function, you can annotate it as `:void`. You can generally drop `:void` and leave it to the inference engine though.\n\n### Optional Parameters\nYou can mark a parameter as optional:\n\n```ts\nfunction foo(bar: number, bas?: string): void {\n    // ..\n}\n\nfoo(123);\nfoo(123, 'hello');\n```\n\nAlternatively you can even provide a default value (using `= someValue` after the parameter declaration) which is injected for you if the caller doesn't provide that argument:\n\n```ts\nfunction foo(bar: number, bas: string = 'hello') {\n    console.log(bar, bas);\n}\n\nfoo(123);           // 123, hello\nfoo(123, 'world');  // 123, world\n```\n\n### Overloading\nTypeScript allows you to *declare* function overloads. This is useful for documentation + type safety purpose. Consider the following code:\n\n```ts\nfunction padding(a: number, b?: number, c?: number, d?: any) {\n    if (b === undefined && c === undefined && d === undefined) {\n        b = c = d = a;\n    }\n    else if (c === undefined && d === undefined) {\n        c = a;\n        d = b;\n    }\n    return {\n        top: a,\n        right: b,\n        bottom: c,\n        left: d\n    };\n}\n```\n\nIf you look at the code carefully you realize the meaning of `a`,`b`,`c`,`d` changes based on how many arguments are passed in. Also the function only expects `1`, `2` or `4` arguments. These constraints can be *enforced* and *documented* using function overloading. You just declare the function header multiple times. The last function header is the one that is actually active *within* the function body but is not available to the outside world.\n\nThis is shown below:\n\n```ts\n// Overloads\nfunction padding(all: number);\nfunction padding(topAndBottom: number, leftAndRight: number);\nfunction padding(top: number, right: number, bottom: number, left: number);\n// Actual implementation that is a true representation of all the cases the function body needs to handle\nfunction padding(a: number, b?: number, c?: number, d?: number) {\n    if (b === undefined && c === undefined && d === undefined) {\n        b = c = d = a;\n    }\n    else if (c === undefined && d === undefined) {\n        c = a;\n        d = b;\n    }\n    return {\n        top: a,\n        right: b,\n        bottom: c,\n        left: d\n    };\n}\n```\n\nHere the first three function headers are available as valid calls to `padding`:\n\n```ts\npadding(1); // Okay: all\npadding(1,1); // Okay: topAndBottom, leftAndRight\npadding(1,1,1,1); // Okay: top, right, bottom, left\n\npadding(1,1,1); // Error: Not a part of the available overloads\n```\n\nOf course it's important for the final declaration (the true declaration as seen from inside the function) to be compatible with all the overloads. This is because that is the true nature of the function calls that the function body needs to account for.\n\n> Function overloading in TypeScript doesn't come with any runtime overhead. It just allows you to document the manner you expect the function to be called in and the compiler holds the rest of your code in check.\n\n### Declaring Functions\n> Quick Tip: *Type Declarations* are how you describe the types of existing implementations. \n\nThere are two ways to *declare* the type of a function without providing an implementation. E.g. \n\n```ts\ntype LongHand = {\n    (a: number): number;\n};\n\ntype ShortHand = (a: number) => number;\n```\nThe example above are both *exactly* equivalent. The differences exist when you want to add overloads. You can only add overloads in the long hand declaration version e.g. \n\n```ts\ntype LongHandAllowsOverloadDeclarations = {\n    (a: number): number;\n    (a: string): string;\n};\n```\n\n[](### Type Compatibility)\n"
  },
  {
    "path": "docs/types/generics.md",
    "content": "## Generics\n\nThe key motivation for generics is to document meaningful type dependencies between members. The members can be:\n\n* Class instance members\n* Class methods\n* function arguments\n* function return value\n\n## Motivation and samples\n\nConsider the simple `Queue` (first in, first out) data structure implementation. A simple one in TypeScript / JavaScript looks like:\n\n```ts\nclass Queue {\n  private data = [];\n  push(item) { this.data.push(item); }\n  pop() { return this.data.shift(); }\n}\n```\n\nOne issue with this implementation is that it allows people to add *anything* to the queue and when they pop it - it can be *anything*. This is shown below, where someone can push a `string` onto the queue while the usage actually assumes that only `numbers` were pushed in:\n\n```ts\nclass Queue {\n  private data = [];\n  push(item) { this.data.push(item); }\n  pop() { return this.data.shift(); }\n}\n\nconst queue = new Queue();\nqueue.push(0);\nqueue.push(\"1\"); // Oops a mistake\n\n// a developer walks into a bar\nconsole.log(queue.pop().toPrecision(1));\nconsole.log(queue.pop().toPrecision(1)); // RUNTIME ERROR\n```\n\nOne solution (and in fact the only one in languages that don't support generics) is to go ahead and create *special* classes just for these constraints. E.g. a quick and dirty number queue:\n\n```ts\nclass QueueNumber extends Queue {\n  push(item: number) { super.push(item); }\n  pop(): number { return this.data.shift(); }\n}\n\nconst queue = new QueueNumber();\nqueue.push(0);\nqueue.push(\"1\"); // ERROR : cannot push a string. Only numbers allowed\n\n// ^ if that error is fixed the rest would be fine too\n```\n\nOf course this can quickly become painful e.g. if you want a string queue you have to go through all that effort again. What you really want is a way to say that whatever the type is of the stuff getting *pushed* it should be the same for whatever gets *popped*. This is done easily with a *generic* parameter (in this case, at the class level):\n\n```ts\n/** A class definition with a generic parameter */\nclass Queue<T> {\n  private data = [];\n  push(item: T) { this.data.push(item); }\n  pop(): T | undefined { return this.data.shift(); }\n}\n\n/** Again sample usage */\nconst queue = new Queue<number>();\nqueue.push(0);\nqueue.push(\"1\"); // ERROR : cannot push a string. Only numbers allowed\n\n// ^ if that error is fixed the rest would be fine too\n```\n\nAnother example that we have already seen is that of a *reverse* function, here the constraint is between what gets passed into the function and what the function returns:\n\n```ts\nfunction reverse<T>(items: T[]): T[] {\n    var toreturn = [];\n    for (let i = items.length - 1; i >= 0; i--) {\n        toreturn.push(items[i]);\n    }\n    return toreturn;\n}\n\nvar sample = [1, 2, 3];\nvar reversed = reverse(sample);\nconsole.log(reversed); // 3,2,1\n\n// Safety!\nreversed[0] = '1';     // Error!\nreversed = ['1', '2']; // Error!\n\nreversed[0] = 1;       // Okay\nreversed = [1, 2];     // Okay\n```\n\nIn this section you have seen examples of generics being defined *at class level* and at *function level*. One minor addition worth mentioning is that you can have generics created just for a member function. As a toy example consider the following where we move the `reverse` function into a `Utility` class:\n\n```ts\nclass Utility {\n  reverse<T>(items: T[]): T[] {\n      var toreturn = [];\n      for (let i = items.length - 1; i >= 0; i--) {\n          toreturn.push(items[i]);\n      }\n      return toreturn;\n  }\n}\n```\n\n> TIP: You can call the generic parameter whatever you want. It is conventional to use `T`, `U`, or `V` when you have simple generics. If you have more than one generic argument try to use meaningful names like `TKey` and `TValue`. The convention is to prefix with `T` because generics are also called *templates* in other languages like C++.\n\n\n### Design Pattern: Convenience generic\n\nConsider the function: \n\n```ts\ndeclare function parse<T>(name: string): T;\n```\n\nIn this case you can see that the type `T` is only used in one place. So there is no constraint *between* members. This is equivalent to a type assertion in terms of type safety:\n\n```ts\ndeclare function parse(name: string): any;\n\nconst something = parse('something') as TypeOfSomething;\n```\n\nGenerics used *only once* are no better than an assertion in terms of type safety. That said they do provide *convenience* to your API.\n\nA more obvious example is a function that loads a json response. It returns a promise of *whatever type you pass in*:\n```ts\nconst getJSON = <T>(config: {\n    url: string,\n    headers?: { [key: string]: string },\n  }): Promise<T> => {\n    const fetchConfig = ({\n      method: 'GET',\n      'Accept': 'application/json',\n      'Content-Type': 'application/json',\n      ...(config.headers || {})\n    });\n    return fetch(config.url, fetchConfig)\n      .then<T>(response => response.json());\n  }\n```\n\nNote that you still have to explicitly annotate what you want, but the `getJSON<T>` signature `(config) => Promise<T>` saves you a few key strokes (you don't need to annotate the return type of `loadUsers` as it can be inferred):\n\n```ts\ntype LoadUsersResponse = {\n  users: {\n    name: string;\n    email: string;\n  }[];  // array of user objects\n}\nfunction loadUsers() {\n  return getJSON<LoadUsersResponse>({ url: 'https://example.com/users' });\n}\n```\n\nAlso `Promise<T>` as a return value is definitely better than alternatives like `Promise<any>`.\n\nAnother example is where a generic is only used as an argument: \n\n```ts\ndeclare function send<T>(arg: T): void;\n```\n\nHere the generic `T` can be used to annote the type that you want the argument to match e.g. \n\n```ts\nsend<Something>({\n  x:123,\n  // Also you get autocomplete  \n}); // Will TSError if `x:123` does not match the structure expected for Something\n\n```\n"
  },
  {
    "path": "docs/types/index-signatures.md",
    "content": "# Index Signatures\n\nAn `Object` in JavaScript (and hence TypeScript) can be accessed with a **string** to hold a reference to any other JavaScript **object**.\n\nHere is a quick example:\n\n```ts\nlet foo: any = {};\nfoo['Hello'] = 'World';\nconsole.log(foo['Hello']); // World\n```\n\nWe store a string `\"World\"` under the key `\"Hello\"`. Remember we said it can store any JavaScript **object**, so lets store a class instance just to show the concept:\n\n```ts\nclass Foo {\n  constructor(public message: string){};\n  log(){\n    console.log(this.message)\n  }\n}\n\nlet foo: any = {};\nfoo['Hello'] = new Foo('World');\nfoo['Hello'].log(); // World\n```\n\nAlso remember that we said that it can be accessed with a **string**. If you pass any other object to the index signature the JavaScript runtime actually calls `.toString` on it before getting the result. This is demonstrated below:\n\n```ts\nlet obj = {\n  toString(){\n    console.log('toString called')\n    return 'Hello'\n  }\n}\n\nlet foo: any = {};\nfoo[obj] = 'World'; // toString called\nconsole.log(foo[obj]); // toString called, World\nconsole.log(foo['Hello']); // World\n```\n\nNote that `toString` will get called whenever the `obj` is used in an index position.\n\nArrays are slightly different. For `number` indexing JavaScript VMs will try to optimise (depending on things like is it actually an array and do the structures of items stored match etc.). So `number` should be considered as a valid object accessor in its own right (distinct from `string`). Here is a simple array example:\n\n```ts\nlet foo = ['World'];\nconsole.log(foo[0]); // World\n```\n\nSo that's JavaScript. Now let's look at TypeScript's graceful handling of this concept.\n\n## TypeScript Index Signature\n\nFirst off, because JavaScript *implicitly* calls `toString` on any object index signature, TypeScript will give you an error to prevent beginners from shooting themselves in the foot (I see users shooting themselves in the foot when using JavaScript all the time on stackoverflow):\n\n```ts\nlet obj = {\n  toString(){\n    return 'Hello'\n  }\n}\n\nlet foo: any = {};\n\n// ERROR: the index signature must be string, number ...\nfoo[obj] = 'World';\n\n// FIX: TypeScript forces you to be explicit\nfoo[obj.toString()] = 'World';\n```\n\nThe reason for forcing the user to be explicit is because the default `toString` implementation on an object is pretty awful, e.g. on v8 it always returns `[object Object]`:\n\n```ts\nlet obj = {message:'Hello'}\nlet foo: any = {};\n\n// ERROR: the index signature must be string, number ...\nfoo[obj] = 'World';\n\n// Here is where you actually stored it!\nconsole.log(foo[\"[object Object]\"]); // World\n```\n\nOf course `number` is supported because\n\n1. its needed for excellent Array / Tuple support.\n1. even if you use it for an `obj` its default `toString` implementation is nice (not `[object Object]`).\n\nPoint 2 is shown below:\n\n```ts\nconsole.log((1).toString()); // 1\nconsole.log((2).toString()); // 2\n```\n\nSo lesson 1:\n\n> TypeScript index signatures must be either `string` or `number`\n\nQuick note: `symbols` are also valid and supported by TypeScript. But let's not go there just yet. Baby steps.\n\n### Declaring an index signature\n\nSo we've been using `any` to tell TypeScript to let us do whatever we want. We can actually specify an *index* signature explicitly. E.g. say you want to make sure that anything that is stored in an object using a string conforms to the structure `{message: string}`. This can be done with the declaration `{ [index:string] : {message: string} }`. This is demonstrated below:\n\n```ts\nlet foo:{ [index:string] : {message: string} } = {};\n\n/**\n * Must store stuff that conforms to the structure\n */\n/** Ok */\nfoo['a'] = { message: 'some message' };\n/** Error: must contain a `message` of type string. You have a typo in `message` */\nfoo['a'] = { messages: 'some message' };\n\n/**\n * Stuff that is read is also type checked\n */\n/** Ok */\nfoo['a'].message;\n/** Error: messages does not exist. You have a typo in `message` */\nfoo['a'].messages;\n```\n\n> TIP: the name of the index signature e.g. `index` in `{ [index:string] : {message: string} }` has no significance for TypeScript and is only for readability. e.g. if it's user names you can do `{ [username:string] : {message: string} }` to help the next dev who looks at the code (which just might happen to be you).\n\nOf course `number` indexes are also supported e.g. `{ [count: number] : SomeOtherTypeYouWantToStoreEgRebate }`\n\n### All members must conform to the `string` index signature\n\nAs soon as you have a `string` index signature, all explicit members must also conform to that index signature. This is shown below:\n\n```ts\n/** Okay */\ninterface Foo {\n  [key:string]: number;\n  x: number;\n  y: number;\n}\n/** Error */\ninterface Bar {\n  [key:string]: number;\n  x: number;\n  y: string; // ERROR: Property `y` must be of type number\n}\n```\n\nThis is to provide safety so that any string access gives the same result:\n\n```ts\ninterface Foo {\n  [key:string]: number;\n  x: number;\n}\nlet foo: Foo = {x:1,y:2};\n\n// Directly\nfoo['x']; // number\n\n// Indirectly\nlet x = 'x'\nfoo[x]; // number\n```\n\n### Using a limited set of string literals\n\nAn index signature can require that index strings be members of a union of literal strings by using *Mapped Types* e.g.:\n\n```ts\ntype Index = 'a' | 'b' | 'c'\ntype FromIndex = { [k in Index]?: number }\n\nconst good: FromIndex = {b:1, c:2}\n\n// Error:\n// Type '{ b: number; c: number; d: number; }' is not assignable to type 'FromIndex'.\n// Object literal may only specify known properties, and 'd' does not exist in type 'FromIndex'.\nconst bad: FromIndex = {b:1, c:2, d:3};\n```\n\nThis is often used together with `keyof typeof` to capture vocabulary types, described on the next page.\n\nThe specification of the vocabulary can be deferred generically:\n\n```ts\ntype FromSomeIndex<K extends string> = { [key in K]: number }\n```\n\n### Having both `string` and `number` indexers\n\nThis is not a common use case, but TypeScript compiler supports it nonetheless.\n\nHowever, it has the restriction that the `string` indexer is more strict than the `number` indexer. This is intentional e.g. to allow typing stuff like:\n\n```ts\ninterface ArrStr {\n  [key: string]: string | number; // Must accommodate all members\n\n  [index: number]: string; // Can be a subset of string indexer\n\n  // Just an example member\n  length: number;\n}\n```\n\n### Design Pattern: Nested index signature\n\n> API consideration when adding index signatures\n\nQuite commonly in the JS community you will see APIs that abuse string indexers. e.g. a common pattern among CSS in JS libraries:\n\n```ts\ninterface NestedCSS {\n  color?: string;\n  [selector: string]: string | NestedCSS | undefined;\n}\n\nconst example: NestedCSS = {\n  color: 'red',\n  '.subclass': {\n    color: 'blue'\n  }\n}\n```\n\nTry not to mix string indexers with *valid* values this way. E.g. a typo in the padding will remain uncaught:\n\n```ts\nconst failsSilently: NestedCSS = {\n  colour: 'red', // No error as `colour` is a valid string selector\n}\n```\n\nInstead separate out the nesting into its own property e.g. in a name like `nest` (or `children` or `subnodes` etc.):\n\n```ts\ninterface NestedCSS {\n  color?: string;\n  nest?: {\n    [selector: string]: NestedCSS;\n  }\n}\n\nconst example: NestedCSS = {\n  color: 'red',\n  nest: {\n    '.subclass': {\n      color: 'blue'\n    }\n  }\n}\n\nconst failsSilently: NestedCSS = {\n  colour: 'red', // TS Error: unknown property `colour`\n}\n```\n\n### Excluding certain properties from the index signature\n\nSometimes you need to combine properties into the index signature. This is not advised, and you *should* use the Nested index signature pattern mentioned above. \n\nHowever, if you are modeling *existing JavaScript* you can get around it with an intersection type. The following shows an example of the error you will encounter without using an intersection:\n\n```ts\ntype FieldState = {\n  value: string\n}\n\ntype FormState = {\n  isValid: boolean  // Error: Does not conform to the index signature\n  [fieldName: string]: FieldState\n}\n```\n\nHere is the workaround using an intersection type:\n\n```ts\ntype FieldState = {\n  value: string\n}\n\ntype FormState =\n  { isValid: boolean }\n  & { [fieldName: string]: FieldState }\n```\n\nNote that even though you can declare it to model existing JavaScript, you cannot create such an object using TypeScript:  \n\n```ts\ntype FieldState = {\n  value: string\n}\n\ntype FormState =\n  { isValid: boolean }\n  & { [fieldName: string]: FieldState }\n\n\n// Use it for some JavaScript object you are getting from somewhere \ndeclare const foo:FormState; \n\nconst isValidBool = foo.isValid;\nconst somethingFieldState = foo['something'];\n\n// Using it to create a TypeScript object will not work\nconst bar: FormState = { // Error `isValid` not assignable to `FieldState\n  isValid: false\n}\n```\n"
  },
  {
    "path": "docs/types/interfaces.md",
    "content": "## Interfaces\n\nInterfaces have *zero* runtime JS impact. There is a lot of power in TypeScript interfaces to declare the structure of variables.\n\nThe following two are equivalent declarations, the first uses an *inline annotation*, the second uses an *interface*:\n\n```ts\n// Sample A\ndeclare var myPoint: { x: number; y: number; };\n\n// Sample B\ninterface Point {\n    x: number; y: number;\n}\ndeclare var myPoint: Point;\n```\n\nHowever, the beauty of *Sample B* is that if someone authors a library that builds on the `myPoint` library to add new members, they can easily add to the existing declaration of `myPoint`:\n\n```ts\n// Lib a.d.ts\ninterface Point {\n    x: number; y: number;\n}\ndeclare var myPoint: Point;\n\n// Lib b.d.ts\ninterface Point {\n    z: number;\n}\n\n// Your code\nvar myPoint.z; // Allowed!\n```\n\nThis is because **interfaces in TypeScript are open ended**. This is a vital tenet of TypeScript that it allows you to mimic the extensibility of JavaScript using *interfaces*.\n\n\n## Classes can implement interfaces\n\nIf you want to use *classes* that must follow an object structure that someone declared for you in an `interface` you can use the `implements` keyword to ensure compatibility:\n\n```ts\ninterface Point {\n    x: number; y: number;\n}\n\nclass MyPoint implements Point {\n    x: number; y: number; // Same as Point\n}\n```\n\nBasically in the presence of that `implements`, any changes in that external `Point` interface will result in a compile error in your code base so you can easily keep it in sync:\n\n```ts\ninterface Point {\n    x: number; y: number;\n    z: number; // New member\n}\n\nclass MyPoint implements Point { // ERROR : missing member `z`\n    x: number; y: number;\n}\n```\n\nNote that `implements` restricts the structure of the class *instances* i.e.:\n\n```ts\nvar foo: Point = new MyPoint();\n```\n\nAnd stuff like `foo: Point = MyPoint` is not the same thing.\n\n\n## TIPs\n\n### Not every interface is implementable easily\n\nInterfaces are designed to declare *any arbitrarily crazy* structure that might be present in JavaScript.\n\nConsider the following interface where something is callable with `new`:\n\n```ts\ninterface Crazy {\n    new (): {\n        hello: number\n    };\n}\n```\n\nYou would essentially have something like:\n\n```ts\nclass CrazyClass implements Crazy {\n    constructor() {\n        return { hello: 123 };\n    }\n}\n// Because\nconst crazy = new CrazyClass(); // crazy would be {hello:123}\n```\n\nYou can *declare* all the crazy JS out there with interfaces and even use them safely from TypeScript. Doesn't mean you can use TypeScript classes to implement them.\n"
  },
  {
    "path": "docs/types/lib.d.ts.md",
    "content": "* [lib.d.ts](#libdts)\n* [Example Usage](#example-usage)\n* [Inside look](#libdts-inside-look)\n* [Modifying Native types](#modifying-native-types)\n* [Using custom lib.d.ts](#using-your-own-custom-libdts)\n* [Compiler `target` effect on lib.d.ts](#compiler-target-effect-on-libdts)\n* [`lib` option](#lib-option)\n* [Polyfill for old JavaScript engines](#polyfill-for-old-javascript-engines)\n\n## `lib.d.ts`\n\nA special declaration file `lib.d.ts` ships with every installation of TypeScript. This file contains the ambient declarations for various common JavaScript constructs present in JavaScript runtimes and the DOM.\n\n* This file is automatically included in the compilation context of a TypeScript project.\n* The objective of this file is to make it easy for you to start writing *type checked* JavaScript code.\n\nYou can exclude this file from the compilation context by specifying the `--noLib` compiler command line flag (or `\"noLib\" : true` in `tsconfig.json`).\n\n### Example Usage\n\nAs always let's look at examples of this file being used in action:\n\n```ts\nvar foo = 123;\nvar bar = foo.toString();\n```\nThis code type checks fine *because* the `toString` function is defined in `lib.d.ts` for all JavaScript objects.\n\nIf you use the same sample code with the `noLib` option you get a type check error:\n\n```ts\nvar foo = 123;\nvar bar = foo.toString(); // ERROR: Property 'toString' does not exist on type 'number'.\n```\nSo now that you understand the importance of `lib.d.ts`, what do its contents look like? We examine that next.\n\n### `lib.d.ts` Inside Look\n\nThe contents of `lib.d.ts` are primarily a bunch of *variable* declarations e.g. `window`, `document`, `math` and a bunch of similar *interface* declarations e.g. `Window` , `Document`, `Math`.\n\nThe simplest way to read the documentation and type annotations of global stuff is to type in code *that you know works* e.g. `Math.floor` and then F12 (go to definition) using your IDE (VSCode has great support for this).\n\nLet's look at a sample *variable* declaration, e.g. `window` is defined as:\n```ts\ndeclare var window: Window;\n```\nThat is just a simple `declare var` followed by the variable name (here `window`) and an interface for a type annotation (here the `Window` interface). These variables generally point to some global *interface* e.g. here is a small sample of the (actually quite massive) `Window` interface:\n\n```ts\ninterface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64 {\n    animationStartTime: number;\n    applicationCache: ApplicationCache;\n    clientInformation: Navigator;\n    closed: boolean;\n    crypto: Crypto;\n    // so on and so forth...\n}\n```\nYou can see that there is a *lot* of type information in these interfaces. In the absence of TypeScript *you* would need to keep this in *your* head. Now you can offload that knowledge on the compiler with easy access to it using things like `intellisense`.\n\nThere is a good reason for using *interfaces* for these globals. It allows you to *add additional properties* to these globals *without* a need to change `lib.d.ts`. We will cover this concept next.\n\n### Modifying Native Types\n\nSince an `interface` in TypeScript is open ended this means that you can just add members to the interfaces declared in `lib.d.ts` and TypeScript will pick up on the additions. Note that you need to make these changes in a [*global module*](../project/modules.md) for these interfaces to be associated with `lib.d.ts`. We even recommend creating a special file called [`global.d.ts`](../project/globals.md) for this purpose.\n\nHere are a few example cases where we add stuff to `window`, `Math`, `Date`:\n\n#### Example `window`\n\nJust add stuff to the `Window` interface e.g.:\n\n```ts\ninterface Window {\n    helloWorld(): void;\n}\n```\n\nThis will allow you to use it in a *type safe* manner:\n\n```ts\n// Add it at runtime\nwindow.helloWorld = () => console.log('hello world');\n// Call it\nwindow.helloWorld();\n// Misuse it and you get an error:\nwindow.helloWorld('gracius'); // Error: Supplied parameters do not match the signature of the call target\n```\n\n#### Example `Math`\nThe global variable `Math` is defined in `lib.d.ts` as (again, use your dev tools to navigate to definition):\n\n```ts\n/** An intrinsic object that provides basic mathematics functionality and constants. */\ndeclare var Math: Math;\n```\n\ni.e. the variable `Math` is an instance of the `Math` interface. The `Math` interface is defined as:\n\n```ts\ninterface Math {\n    E: number;\n    LN10: number;\n    // others ...\n}\n```\n\nThis means that if you want to add stuff to the `Math` global variable you just need to add it to the `Math` global interface, e.g. consider the [`seedrandom` project](https://www.npmjs.com/package/seedrandom) which adds a `seedrandom` function to the global `Math` object. This can be declared quite easily:\n\n```ts\ninterface Math {\n    seedrandom(seed?: string);\n}\n```\n\nAnd then you can just use it:\n\n```ts\nMath.seedrandom();\n// or\nMath.seedrandom(\"Any string you want!\");\n```\n\n#### Example `Date`\n\nIf you look at the definition of the `Date` *variable* in `lib.d.ts` you will find:\n\n```ts\ndeclare var Date: DateConstructor;\n```\nThe interface `DateConstructor` is similar to what you have seen before with `Math` and `Window` in that it contains members you can use off of the `Date` global variable e.g. `Date.now()`. In addition to these members it contains *construct* signatures which allow you to create `Date` instances (e.g. `new Date()`). A snippet of the `DateConstructor` interface is shown below:\n\n```ts\ninterface DateConstructor {\n    new (): Date;\n    // ... other construct signatures\n\n    now(): number;\n    // ... other member functions\n}\n```\n\nConsider the project [`datejs`](https://github.com/abritinthebay/datejs). DateJS adds members to both the `Date` global variable and `Date` instances. Therefore a TypeScript definition for this library would look like ([BTW the community has already written this for you in this case](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/datejs/index.d.ts)):\n\n```ts\n/** DateJS Public Static Methods */\ninterface DateConstructor {\n    /** Gets a date that is set to the current date. The time is set to the start of the day (00:00 or 12:00 AM) */\n    today(): Date;\n    // ... so on and so forth\n}\n\n/** DateJS Public Instance Methods */\ninterface Date {\n    /** Adds the specified number of milliseconds to this instance. */\n    addMilliseconds(milliseconds: number): Date;\n    // ... so on and so forth\n}\n```\nThis allows you to do stuff like the following in a TypeSafe manner:\n\n```ts\nvar today = Date.today();\nvar todayAfter1second = today.addMilliseconds(1000);\n```\n\n#### Example `string`\n\nIf you look inside `lib.d.ts` for string you will find stuff similar to what we saw for `Date` (`String` global variable, `StringConstructor` interface, `String` interface). One thing of note though is that the `String` interface also impacts string *literals* as demonstrated in the below code sample:\n\n```ts\n\ninterface String {\n    endsWith(suffix: string): boolean;\n}\n\nString.prototype.endsWith = function(suffix: string): boolean {\n    var str: string = this;\n    return str && str.indexOf(suffix, str.length - suffix.length) !== -1;\n}\n\nconsole.log('foo bar'.endsWith('bas')); // false\nconsole.log('foo bas'.endsWith('bas')); // true\n```\n\nSimilar variables and interfaces exist for other things that have both static and instance members like `Number`, `Boolean`, `RegExp`, etc. and these interfaces affect literal instances of these types as well.\n\n### Example `string` redux\n\nWe recommended creating a `global.d.ts` for maintainability reasons. However, you can break into the *global namespace* from within *a file module* if you desire so. This is done using `declare global { /*global namespace here*/ }`. E.g. the previous example can also be done as:\n\n```ts\n// Ensure this is treated as a module.\nexport {};\n\ndeclare global {\n    interface String {\n        endsWith(suffix: string): boolean;\n    }\n}\n\nString.prototype.endsWith = function(suffix: string): boolean {\n    var str: string = this;\n    return str && str.indexOf(suffix, str.length - suffix.length) !== -1;\n}\n\nconsole.log('foo bar'.endsWith('bas')); // false\nconsole.log('foo bas'.endsWith('bas')); // true\n```\n\n### Using your own custom lib.d.ts\nAs we mentioned earlier, using the `--noLib` boolean compiler flag causes TypeScript to exclude the automatic inclusion of `lib.d.ts`. There are various reasons why this is a useful feature. Here are a few of the common ones:\n\n* You are running in a custom JavaScript environment that differs *significantly* from the standard browser based runtime environment.\n* You like to have *strict* control over the *globals* available in your code. E.g. lib.d.ts defines `item` as a global variable and you don't want this to leak into your code.\n\nOnce you have excluded the default `lib.d.ts` you can include a similarly named file into your compilation context and TypeScript will pick it up for type checking.\n\n> Note: be careful with `--noLib`. Once you are in noLib land, if you choose to share your project with others, they will be *forced* into noLib land (or rather *your lib* land). Even worse, if you bring *their* code into your project you might need to port it to *your lib* based code.\n\n### Compiler target effect on `lib.d.ts`\n\nSetting the compiler target to `es6` causes the `lib.d.ts` to include *additional* ambient declarations for more modern (es6) stuff like `Promise`. This magical effect of the compiler target changing the *ambience* of the code is desirable for some people and for others it's problematic as it conflates *code generation* with *code ambience*.\n\nHowever, if you want finer grained control of your environment, you should use the `--lib` option which we discuss next.\n\n### lib option\n\nSometimes (many times) you want to decouple the relationship between the compile target (the generated JavaScript version) and the ambient library support. A common example is `Promise`, e.g. today (in June 2016) you most likely want to `--target es5` but still use the latest features like `Promise`. To support this you can take explicit control of `lib` using the `lib` compiler option.\n\n> Note: using `--lib` decouples any lib magic from `--target` giving you better control.\n\nYou can provide this option on the command line or in `tsconfig.json` (recommended):\n\n**Command line**:\n```\ntsc --target es5 --lib dom,es6\n```\n**tsconfig.json**:\n```json\n\"compilerOptions\": {\n    \"lib\": [\"dom\", \"es6\"]\n}\n```\n\nThe libs can be categorized as follows:\n\n* JavaScript Bulk Feature:\n    * es5\n    * es6\n    * es2015\n    * es7\n    * es2016\n    * es2017\n    * esnext\n* Runtime Environment\n    * dom\n    * dom.iterable\n    * webworker\n    * scripthost\n* ESNext By-Feature Options (even smaller than bulk feature)\n    * es2015.core\n    * es2015.collection\n    * es2015.generator\n    * es2015.iterable\n    * es2015.promise\n    * es2015.proxy\n    * es2015.reflect\n    * es2015.symbol\n    * es2015.symbol.wellknown\n    * es2016.array.include\n    * es2017.object\n    * es2017.sharedmemory\n    * esnext.asynciterable\n\n> NOTE: the `--lib` option provides extremely fine tuned control. So you most likely want to pick an item from the bulk + environment categories.\n> If --lib is not specified a default library is injected:\n  - For --target es5 => es5, dom, scripthost\n  - For --target es6 => es6, dom, dom.iterable, scripthost\n\nMy Personal Recommendation:\n\n```json\n\"compilerOptions\": {\n    \"target\": \"es5\",\n    \"lib\": [\"es6\", \"dom\"]\n}\n```\n\nExample Including Symbol with ES5:\n\nSymbol API is not included when target is es5. In fact, we receive an error like: [ts] Cannot find name 'Symbol'.\nWe can use \"target\": \"es5\" in combination with \"lib\" to provide Symbol API in TypeScript:\n\n```json\n\"compilerOptions\": {\n    \"target\": \"es5\",\n    \"lib\": [\"es5\", \"dom\", \"scripthost\", \"es2015.symbol\"]\n}\n```\n\n## Polyfill for old JavaScript engines\n\n> [Egghead PRO Video on this subject](https://egghead.io/lessons/typescript-using-es6-and-esnext-with-typescript)\n\nThere are quite a few runtime features that are like `Map` / `Set` and even `Promise` (this list will of course change over time) that you can use with modern `lib` options. To use these all you need to do is use `core-js`. Simply install:\n\n```\nnpm install core-js --save-dev\n```\nAnd add an import to your application entry point: \n\n```js\nimport \"core-js\";\n```\n\nAnd it should polyfill these runtime features for you 🌹.\n"
  },
  {
    "path": "docs/types/literal-types.md",
    "content": "## Literals\nLiterals are *exact* values that are JavaScript primitives. \n\n### String Literals\n\nYou can use a string literal as a type. For example:\n\n```ts\nlet foo: 'Hello';\n```\n\nHere we have created a variable called `foo` that *will only allow the literal value `'Hello'` to be assigned to it*. This is demonstrated below:\n\n```ts\nlet foo: 'Hello';\nfoo = 'Bar'; // Error: \"Bar\" is not assignable to type \"Hello\"\n```\n\nThey are not very useful on their own but can be combined in a type union to create a powerful (and useful) abstraction e.g.:\n\n```ts\ntype CardinalDirection =\n    | \"North\"\n    | \"East\"\n    | \"South\"\n    | \"West\";\n\nfunction move(distance: number, direction: CardinalDirection) {\n    // ...\n}\n\nmove(1,\"North\"); // Okay\nmove(1,\"Nurth\"); // Error!\n```\n\n### Other literal types\nTypeScript also supports `boolean` and `number` literal types, e.g.: \n\n```ts\ntype OneToFive = 1 | 2 | 3 | 4 | 5;\ntype Bools = true | false;\n```\n\n### Inference \nQuite commonly you get an error like `Type string is not assignable to type \"foo\"`. The following example demonstrates this.\n\n```js\nfunction iTakeFoo(foo: 'foo') { }\nconst test = {\n  someProp: 'foo'\n};\niTakeFoo(test.someProp); // Error: Argument of type string is not assignable to parameter of type 'foo'\n```\n\nThis is because `test` is inferred to be of type `{someProp: string}`. The fix here is to use a simple type assertion to tell TypeScript the literal you want it to infer as shown below: \n\n```js\nfunction iTakeFoo(foo: 'foo') { }\nconst test = {\n  someProp: 'foo' as 'foo'\n};\niTakeFoo(test.someProp); // Okay!\n```\n\nor use a type annotation that helps TypeScript infer the correct thing at the point of declaration: \n\n```ts\nfunction iTakeFoo(foo: 'foo') { }\ntype Test = {\n  someProp: 'foo',\n}\nconst test: Test = { // Annotate - inferred someProp is always === 'foo'\n  someProp: 'foo' \n}; \niTakeFoo(test.someProp); // Okay!\n```\n\n### Use cases\nValid use cases for string literal types are:\n\n#### String based enums\n\n[TypeScript enums are number based](../enums.md). You can use string literals with union types to mock a string based enum as we did in the `CardinalDirection` example above. You can even generate a `Key:Value` structure using the following function: \n\n```ts\n/** Utility function to create a K:V from a list of strings */\nfunction strEnum<T extends string>(o: Array<T>): {[K in T]: K} {\n  return o.reduce((res, key) => {\n    res[key] = key;\n    return res;\n  }, Object.create(null));\n}\n```\n\nAnd then generate the literal type union using `keyof typeof`. Here is a complete example:\n\n```ts\n/** Utility function to create a K:V from a list of strings */\nfunction strEnum<T extends string>(o: Array<T>): {[K in T]: K} {\n  return o.reduce((res, key) => {\n    res[key] = key;\n    return res;\n  }, Object.create(null));\n}\n\n/**\n  * Sample create a string enum\n  */\n\n/** Create a K:V */\nconst Direction = strEnum([\n  'North',\n  'South',\n  'East',\n  'West'\n])\n/** Create a Type */\ntype Direction = keyof typeof Direction;\n\n/** \n  * Sample using a string enum\n  */\nlet sample: Direction;\n\nsample = Direction.North; // Okay\nsample = 'North'; // Okay\nsample = 'AnythingElse'; // ERROR!\n```\n\n#### Modelling existing JavaScript APIs\n\nE.g. [CodeMirror editor has an option `readOnly`](https://codemirror.net/doc/manual.html#option_readOnly) that can either be a `boolean` or the literal string `\"nocursor\"` (effective valid values `true,false,\"nocursor\"`).  It can be declared as:\n\n```ts\nreadOnly: boolean | 'nocursor';\n```\n\n#### Discriminated Unions\n\nWe will cover [this later in the book](./discriminated-unions.md).\n\n\n[](https://github.com/Microsoft/TypeScript/pull/5185)\n"
  },
  {
    "path": "docs/types/migrating.md",
    "content": "## Migrating From JavaScript\n\nAssuming:\n* you know JavaScript.\n* you know patterns and build tools (e.g. webpack) used in the project. \n\nWith that assumption out of the way, in general the process consists of the following steps:\n\n* Add a `tsconfig.json`.\n* Change your source code file extensions from `.js` to `.ts`. Start *suppressing* errors using `any`.\n* Write new code in TypeScript and make as little use of `any` as possible.\n* Go back to the old code and start adding type annotations and fix identified bugs.\n* Use ambient definitions for third party JavaScript code.\n\nLet us discuss a few of these points further.\n\nNote that all JavaScript is *valid* TypeScript. That is to say that if you give the TypeScript compiler some JavaScript -> the JavaScript emitted by the TypeScript compiler will behave exactly the same as the original JavaScript. This means that changing the extension from `.js` to `.ts` will not adversely affect your codebase.\n\n### Suppressing Errors\nTypeScript will immediately start TypeChecking your code and your original JavaScript code *might not be as neat as you thought it was* and hence you get diagnostic errors. Many of these errors you can suppress with using `any` e.g.:\n\n```ts\nvar foo = 123;\nvar bar = 'hey';\n\nbar = foo; // ERROR: cannot assign a number to a string\n```\n\nEven though the **error is valid** (and in most cases the inferred information will be better than what the original authors of different portions of the code bases imagined), your focus will probably be writing new code in TypeScript while progressively updating the old code base. Here you can suppress this error with a type assertion as shown below:\n\n```ts\nvar foo = 123;\nvar bar = 'hey';\n\nbar = foo as any; // Okay!\n```\n\nIn other places you might want to annotate something as `any` e.g.:\n\n```ts\nfunction foo() {\n    return 1;\n}\nvar bar = 'hey';\nbar = foo(); // ERROR: cannot assign a number to a string\n```\n\nSuppressed:\n\n```ts\nfunction foo(): any { // Added `any`\n    return 1;\n}\nvar bar = 'hey';\nbar = foo(); // Okay!\n```\n\n> Note: Suppressing errors is dangerous, but it allows you to take notice of errors in your *new* TypeScript code. You might want to leave `// TODO:` comments as you go along.**\n\n### Third Party JavaScript\nYou can change your JavaScript to TypeScript, but you can't change the whole world to use TypeScript. This is where TypeScript's ambient definition support comes in. In the beginning we recommend you create a `vendor.d.ts` (the `.d.ts` extension specifies the fact that this is a *declaration file*) and start adding dirty stuff to it. Alternatively create a file specific for the library e.g. `jquery.d.ts` for jquery.\n\n> Note: Well maintained and strongly typed definitions for nearly the top 90% JavaScript libraries out there exists in an OSS Repository called [DefinitelyTyped](https://github.com/borisyankov/DefinitelyTyped). We recommend looking there before creating your own definitions as we present here. Nevertheless this quick and dirty way is vital knowledge to decrease your initial friction with TypeScript**.\n\nConsider the case of `jquery`, you can create a *trivial* definition for it quite easily:\n\n```ts\ndeclare var $: any;\n```\n\nSometimes you might want to add an explicit annotation on something (e.g. `JQuery`) and you need something in *type declaration space*. You can do that quite easily using the `type` keyword:\n\n```ts\ndeclare type JQuery = any;\ndeclare var $: JQuery;\n```\n\nThis provides you an easier future update path.\n\nAgain, a high quality `jquery.d.ts` exists at [DefinitelyTyped](https://github.com/borisyankov/DefinitelyTyped). But you now know how to overcome any JavaScript -> TypeScript friction *quickly* when using third party JavaScript. We will look at ambient declarations in detail next.\n\n\n# Third Party NPM modules\n\nSimilar to global variable declaration you can declare a global module quite easily. E.g. for `jquery` if you want to use it as a module (https://www.npmjs.com/package/jquery) you can write the following yourself: \n\n```ts\ndeclare module \"jquery\";\n```\n\nAnd then you can import it in your file as needed: \n\n```ts\nimport * as $ from \"jquery\";\n```\n\n> Again, a high quality `jquery.d.ts` exists at [DefinitelyTyped](https://github.com/borisyankov/DefinitelyTyped) that provides a much higher quality jquery module declaration. But it might not exist for your library, so now you have a quick low friction way of continuing the migration 🌹\n\n# External non js resources\n\nYou can even allow import of any file e.g. `.css` files (if you are using something like webpack style loaders or css modules) with a simple `*` style declaration (ideally in a [`global.d.ts` file](../project/globals.md)): \n\n```ts\ndeclare module \"*.css\";\n```\n\nNow people can `import * as foo from \"./some/file.css\";`\n\nSimilarly if you are using html templates (e.g. angular) you can: \n\n```ts\ndeclare module \"*.html\";\n```\n\n# More \nIf you want to be more silent about your upgrade because you couldn't get team buy in to move to TypeScript, [TypeScript has a blog post on upgrading silently without having to convince your team up front](https://devblogs.microsoft.com/typescript/how-to-upgrade-to-typescript-without-anybody-noticing-part-1/).\n"
  },
  {
    "path": "docs/types/mixins.md",
    "content": "# Mixins\n\nTypeScript (and JavaScript) classes support strict single inheritance. So you *cannot* do:\n\n```ts\nclass User extends Tagged, Timestamped { // ERROR : no multiple inheritance\n}\n```\n\nAnother way of building up classes from reusable components is to build them by combining simpler partial classes called mixins.\n\nThe idea is simple, instead of a *class A extending class B* to get its functionality, *function B takes class A* and returns a new class with this added functionality. Function `B` is a mixin.  \n\n> [A mixin is] a function that\n>\n> 1. takes a constructor,\n> 1. creates a class that extends that constructor with new functionality\n> 1. returns the new class\n\nA complete example\n\n```ts\n// Needed for all mixins\ntype Constructor<T = {}> = new (...args: any[]) => T;\n\n////////////////////\n// Example mixins\n////////////////////\n\n// A mixin that adds a property\nfunction Timestamped<TBase extends Constructor>(Base: TBase) {\n  return class extends Base {\n    timestamp = Date.now();\n  };\n}\n\n// a mixin that adds a property and methods\nfunction Activatable<TBase extends Constructor>(Base: TBase) {\n  return class extends Base {\n    isActivated = false;\n\n    activate() {\n      this.isActivated = true;\n    }\n\n    deactivate() {\n      this.isActivated = false;\n    }\n  };\n}\n\n////////////////////\n// Usage to compose classes\n////////////////////\n\n// Simple class\nclass User {\n  name = '';\n}\n\n// User that is Timestamped\nconst TimestampedUser = Timestamped(User);\n\n// User that is Timestamped and Activatable\nconst TimestampedActivatableUser = Timestamped(Activatable(User));\n\n////////////////////\n// Using the composed classes\n////////////////////\n\nconst timestampedUserExample = new TimestampedUser();\nconsole.log(timestampedUserExample.timestamp);\n\nconst timestampedActivatableUserExample = new TimestampedActivatableUser();\nconsole.log(timestampedActivatableUserExample.timestamp);\nconsole.log(timestampedActivatableUserExample.isActivated);\n\n```\n\nLet's decompose this example.\n\n## Take a constructor\n\nMixins take a class and extend it with new functionality. So we need to define what is a *constructor*. Easy as:\n\n```ts\n// Needed for all mixins\ntype Constructor<T = {}> = new (...args: any[]) => T;\n```\n\n## Extend the class and return it\n\nPretty easy:\n\n```ts\n// A mixin that adds a property\nfunction Timestamped<TBase extends Constructor>(Base: TBase) {\n  return class extends Base {\n    timestamp = Date.now();\n  };\n}\n```\n\nAnd that is it 🌹\n"
  },
  {
    "path": "docs/types/moving-types.md",
    "content": "# Moving Types\n\nTypeScript's type system is extremely powerful and allows moving and slicing types in ways not possible in any other single language out there.\n\nThis is because TypeScript is designed to allow you to work seamlessly with a *highly dynamic* language like JavaScript. Here we cover a few tricks for moving types around in TypeScript.\n\nKey motivation for these : You change one thing and everything else just updates automatically and you get nice errors if something is going to break, like a well designed constraint system.\n\n## Copying both the Type + Value\n\nIf you want to move a class around, you might be tempted to do the following:\n\n```ts\nclass Foo { }\nvar Bar = Foo;\nvar bar: Bar; // ERROR: cannot find name 'Bar'\n```\n\nThis is an error because `var` only copied the `Foo` into the *variable* declaration space and you therefore cannot use `Bar` as a type annotation. The proper way is to use the `import` keyword. Note that you can only use the `import` keyword in such a way if you are using *namespaces* or *modules* (more on these later):\n\n```ts\nnamespace importing {\n    export class Foo { }\n}\n\nimport Bar = importing.Foo;\nvar bar: Bar; // Okay\n```\n\nThis `import` trick only works for things that are *both type and variable*.\n\n## Capturing the type of a variable\n\nYou can actually use a variable in a type annotation using the `typeof` operator. This allows you to tell the compiler that one variable is the same type as another. Here is an example to demonstrate this:\n\n```ts\nvar foo = 123;\nvar bar: typeof foo; // `bar` has the same type as `foo` (here `number`)\nbar = 456; // Okay\nbar = '789'; // ERROR: Type `string` is not `assignable` to type `number`\n```\n\n## Capturing the type of a class member\n\nYou can traverse into any non-nullable object type to retrieve the type of a property:\n\n```ts\nclass Foo {\n  foo: number; // some member whose type we want to capture\n}\n\nlet bar: Foo['foo']; // `bar` has type `number`\n```\n\nAlternatively, similar to capturing the type of a variable, you just declare a variable purely for type capturing purposes:\n\n```ts\n// Purely to capture type\ndeclare let _foo: Foo;\n\n// Same as before\nlet bar: typeof _foo.foo; // `bar` has type `number`\n```\n\n## Capturing the type of magic strings\n\nLots of JavaScript libraries and frameworks work off of raw JavaScript strings. You can use `const` variables to capture their type e.g.\n\n```ts\n// Capture both the *type* _and_ *value* of magic string:\nconst foo = \"Hello World\";\n\n// Use the captured type:\nlet bar: typeof foo;\n\n// bar can only ever be assigned to `Hello World`\nbar = \"Hello World\"; // Okay!\nbar = \"anything else \"; // Error!\n```\n\nIn this example `bar` has the literal type `\"Hello World\"`. We cover this more in the [literal type section](./literal-types.md).\n\n## Capturing Key Names\n\nThe `keyof` operator lets you capture the key names of a type. E.g. you can use it to capture the key names of a variable by first grabbing its type using `typeof`:\n\n```ts\nconst colors = {\n  red: 'reddish',\n  blue: 'bluish'\n}\ntype Colors = keyof typeof colors;\n\nlet color: Colors; // same as let color: \"red\" | \"blue\"\ncolor = 'red'; // okay\ncolor = 'blue'; // okay\ncolor = 'anythingElse'; // Error: Type '\"anythingElse\"' is not assignable to type '\"red\" | \"blue\"'\n```\n\nThis allows you to have stuff like string enums + constants quite easily, as you just saw in the above example.\n"
  },
  {
    "path": "docs/types/never.md",
    "content": "# Never\n> [Professional Lesson on BooleanArt](https://www.booleanart.com/course/typescript/never)\n\n> [Youtube: Video lesson on the never type](https://www.youtube.com/watch?v=aldIFYWu6xc)\n\n> [Egghead: Video lesson on the never type](https://egghead.io/lessons/typescript-use-the-never-type-to-avoid-code-with-dead-ends-using-typescript)\n\nProgramming language design does have a concept of *bottom* type that is a **natural** outcome as soon as you do *code flow analysis*. TypeScript does *code flow analysis* (😎) and so it needs to reliably represent stuff that might never happen.\n\nThe `never` type is used in TypeScript to denote this *bottom* type. Cases when it occurs naturally:\n\n* A function never returns (e.g. if the function body has `while(true){}`)\n* A function always throws (e.g. in `function foo(){throw new Error('Not Implemented')}` the return type of `foo` is `never`)\n\nOf course you can use this annotation yourself as well\n\n```ts\nlet foo: never; // Okay\n```\n\nHowever, *only `never` can be assigned to another never*. e.g.\n\n```ts\nlet foo: never = 123; // Error: Type number is not assignable to never\n\n// Okay as the function's return type is `never`\nlet bar: never = (() => { throw new Error(`Throw my hands in the air like I just don't care`) })();\n```\n\nGreat. Now let's just jump into its key use case :)\n\n# Use case: Exhaustive Checks\n\nYou can call never functions in a never context.\n\n```ts\nfunction foo(x: string | number): boolean {\n  if (typeof x === \"string\") {\n    return true;\n  } else if (typeof x === \"number\") {\n    return false;\n  }\n\n  // Without a never type we would error :\n  // - Not all code paths return a value (strict null checks)\n  // - Or Unreachable code detected\n  // But because TypeScript understands that `fail` function returns `never`\n  // It can allow you to call it as you might be using it for runtime safety / exhaustive checks.\n  return fail(\"Unexhaustive!\");\n}\n\nfunction fail(message: string): never { throw new Error(message); }\n```\n\nAnd because `never` is only assignable to another `never` you can use it for *compile time* exhaustive checks as well. This is covered in the [*discriminated union* section](./discriminated-unions.md).\n\n# Confusion with `void`\n\nAs soon as someone tells you that `never` is returned when a function never exits gracefully you intuitively want to think of it as the same as `void`. However, `void` is a Unit. `never` is a falsum.\n\nA function that *returns* nothing returns a Unit `void`. However, a function *that never returns* (or always throws) returns `never`. `void` is something that can be assigned (without `strictNullChecking`) but `never` can *never* be assigned to anything other than `never`.\n\n# Type inference in never returning functions\n\nFor function declarations TypeScript infers `void` by default as shown below:\n\n```ts\n// Inferred return type: void\nfunction failDeclaration(message: string) {\n  throw new Error(message);\n}\n\n// Inferred return type: never\nconst failExpression = function(message: string) {\n  throw new Error(message);\n};\n```\n\nOf course you can fix it by an explict annotation: \n\n```ts\nfunction failDeclaration(message: string): never {\n  throw new Error(message);\n}\n```\n\nKey reason is backword compatability with real world JavaScript code: \n\n```ts\nclass Base {\n    overrideMe() {\n        throw new Error(\"You forgot to override me!\");\n    }\n}\n\nclass Derived extends Base {\n    overrideMe() {\n        // Code that actually returns here\n    }\n}\n```\n\nIf `Base.overrideMe` . \n\n> Real world TypeScript can overcome this with `abstract` functions but this inferrence is maintained for compatability.\n\n<!--\nPR: https://github.com/Microsoft/TypeScript/pull/8652\nIssue : https://github.com/Microsoft/TypeScript/issues/3076\nConcept : https://en.wikipedia.org/wiki/Bottom_type\n-->\n"
  },
  {
    "path": "docs/types/readonly.md",
    "content": "## readonly\nTypeScript's type system allows you to mark individual properties on an interface as `readonly`. This allows you to work in a functional way (unexpected mutation is bad):\n\n```ts\nfunction foo(config: {\n    readonly bar: number,\n    readonly bas: number\n}) {\n    // ..\n}\n\nlet config = { bar: 123, bas: 123 };\nfoo(config);\n// You can be sure that `config` isn't changed 🌹\n```\n\nOf course you can use `readonly` in `interface` and `type` definitions as well e.g.:\n\n```ts\ntype Foo = {\n    readonly bar: number;\n    readonly bas: number;\n}\n\n// Initialization is okay\nlet foo: Foo = { bar: 123, bas: 456 };\n\n// Mutation is not\nfoo.bar = 456; // Error: Left-hand side of assignment expression cannot be a constant or a read-only property\n```\n\nYou can even declare a class property as `readonly`. You can initialize them at the point of declaration or in the constructor as shown below:\n\n```ts\nclass Foo {\n    readonly bar = 1; // OK\n    readonly baz: string;\n    constructor() {\n        this.baz = \"hello\"; // OK\n    }\n}\n```\n\n## Readonly\nThere is a type `Readonly` that takes a type `T` and marks all of its properties as `readonly` using mapped types. Here is a demo that uses it in practice: \n\n```ts\ntype Foo = {\n  bar: number;\n  bas: number;\n}\n\ntype FooReadonly = Readonly<Foo>; \n\nlet foo: Foo = {bar: 123, bas: 456};\nlet fooReadonly: FooReadonly = {bar: 123, bas: 456};\n\nfoo.bar = 456; // Okay\nfooReadonly.bar = 456; // ERROR: bar is readonly\n```\n\n### Various Use Cases\n\n#### ReactJS\nOne library that loves immutability is ReactJS, you *could* mark your `Props` and `State` to be immutable e.g.:\n\n```ts\ninterface Props {\n    readonly foo: number;\n}\ninterface State {\n    readonly bar: number;\n}\nexport class Something extends React.Component<Props,State> {\n  someMethod() {\n    // You can rest assured no one is going to do\n    this.props.foo = 123; // ERROR: (props are immutable)\n    this.state.baz = 456; // ERROR: (one should use this.setState)  \n  }\n}\n```\n\nYou do not need to, however, as the type definitions for React mark these as `readonly` already (by internally wrapping the passed in generic types with the `Readonly` type mentioned above).\n\n```ts\nexport class Something extends React.Component<{ foo: number }, { baz: number }> {\n  // You can rest assured no one is going to do\n  someMethod() {\n    this.props.foo = 123; // ERROR: (props are immutable)\n    this.state.baz = 456; // ERROR: (one should use this.setState)  \n  }\n}\n```\n\n#### Seamless Immutable\n\nYou can even mark index signatures as readonly:\n\n```ts\n/**\n * Declaration\n */\ninterface Foo {\n    readonly[x: number]: number;\n}\n\n/**\n * Usage\n */\nlet foo: Foo = { 0: 123, 2: 345 };\nconsole.log(foo[0]);   // Okay (reading)\nfoo[0] = 456;          // Error (mutating): Readonly\n```\n\nThis is great if you want to use native JavaScript arrays in an *immutable* fashion. In fact TypeScript ships with a `ReadonlyArray<T>` interface to allow you to do just that:\n\n```ts\nlet foo: ReadonlyArray<number> = [1, 2, 3];\nconsole.log(foo[0]);   // Okay\nfoo.push(4);           // Error: `push` does not exist on ReadonlyArray as it mutates the array\nfoo = foo.concat([4]); // Okay: create a copy\n```\n\n#### Automatic Inference\nIn some cases the compiler can automatically infer a particular item to be readonly e.g. within a class if you have a property that only has a getter but no setter, it is assumed readonly e.g.:\n\n```ts\nclass Person {\n    firstName: string = \"John\";\n    lastName: string = \"Doe\";\n    get fullName() {\n        return this.firstName + this.lastName;\n    }\n}\n\nconst person = new Person();\nconsole.log(person.fullName); // John Doe\nperson.fullName = \"Dear Reader\"; // Error! fullName is readonly\n```\n\n### Difference from `const`\n`const`\n\n1. is for a variable reference\n1. the variable cannot be reassigned to anything else.\n\n`readonly` is\n\n1. for a property\n1. the property can be modified because of aliasing\n\nSample explaining 1:\n\n```ts\nconst foo = 123; // variable reference\nvar bar: {\n    readonly bar: number; // for property\n}\n```\n\nSample explaining 2:\n\n```ts\nlet foo: {\n    readonly bar: number;\n} = {\n        bar: 123\n    };\n\nfunction iMutateFoo(foo: { bar: number }) {\n    foo.bar = 456;\n}\n\niMutateFoo(foo); // The foo argument is aliased by the foo parameter\nconsole.log(foo.bar); // 456!\n```\n\nBasically `readonly` ensures that a property *cannot be modified by me*, but if you give it to someone that doesn't have that guarantee (allowed for type compatibility reasons) they can modify it. Of course if `iMutateFoo` said that they do not mutate `foo.bar` the compiler would correctly flag it as an error as shown:\n\n```ts\ninterface Foo {\n    readonly bar: number;\n}\nlet foo: Foo = {\n    bar: 123\n};\n\nfunction iTakeFoo(foo: Foo) {\n    foo.bar = 456; // Error! bar is readonly\n}\n\niTakeFoo(foo); // The foo argument is aliased by the foo parameter\n```\n\n[](https://github.com/Microsoft/TypeScript/pull/6532)\n"
  },
  {
    "path": "docs/types/type-assertion.md",
    "content": "## Type Assertion\nTypeScript allows you to override its inferred and analyzed view of types in any way you want to. This is done by a mechanism called \"type assertion\". TypeScript's type assertion is purely you telling the compiler that you know about the types better than it does, and that it should not second guess you.\n\nA common use case for type assertion is when you are porting over code from JavaScript to TypeScript. For example consider the following pattern:\n\n```ts\nvar foo = {};\nfoo.bar = 123; // Error: property 'bar' does not exist on `{}`\nfoo.bas = 'hello'; // Error: property 'bas' does not exist on `{}`\n```\n\nHere the code errors because the *inferred* type of `foo` is `{}` i.e. an object with zero properties. Therefore you are not allowed to add `bar` or `bas` to it. You can fix this simply by a type assertion `as Foo`:\n\n```ts\ninterface Foo {\n    bar: number;\n    bas: string;\n}\nvar foo = {} as Foo;\nfoo.bar = 123;\nfoo.bas = 'hello';\n```\n\n### `as foo` vs. `<foo>`\nOriginally the syntax that was added was `<foo>`. This is demonstrated below:\n\n```ts\nvar foo: any;\nvar bar = <string> foo; // bar is now of type \"string\"\n```\n\nHowever, there is an ambiguity in the language grammar when using `<foo>` style assertions in JSX:\n\n```ts\nvar foo = <string>bar;\n</string>\n```\n\nTherefore it is now recommended that you just use `as foo` for consistency.\n\n### Type Assertion vs. Casting\nThe reason why it's not called \"type casting\" is that *casting* generally implies some sort of runtime support. However, *type assertions* are purely a compile time construct and a way for you to provide hints to the compiler on how you want your code to be analyzed.\n\n### Assertion considered harmful\nIn many cases assertion will allow you to easily migrate legacy code (and even copy paste other code samples into your codebase). However, you should be careful with your use of assertions. Take our original code as a sample, the compiler will not protect you from forgetting to *actually add the properties you promised*:\n\n```ts\ninterface Foo {\n    bar: number;\n    bas: string;\n}\nvar foo = {} as Foo;\n// ahhhh .... forget something?\n```\n\nAlso another common thought is using an assertion as a means of providing *autocomplete* e.g.:\n\n```ts\ninterface Foo {\n    bar: number;\n    bas: string;\n}\nvar foo = <Foo>{\n    // the compiler will provide autocomplete for properties of Foo\n    // But it is easy for the developer to forget adding all the properties\n    // Also this code is likely to break if Foo gets refactored (e.g. a new property added)\n};\n```\n\nbut the hazard here is the same, if you forget a property the compiler will not complain. It is better if you do the following:\n\n```ts\ninterface Foo {\n    bar: number;\n    bas: string;\n}\nvar foo: Foo = {\n    // the compiler will provide autocomplete for properties of Foo\n};\n```\n\nIn some cases you might need to create a temporary variable, but at least you will not be making (possibly false) promises and instead relying on the type inference to do the checking for you.\n\n### Double assertion\n\n> [Pro Video Lesson on Double Assertion](https://www.booleanart.com/course/typescript/double-assertion)\n\nThe type assertion, despite being a bit unsafe as we've shown, is not *completely open season*. E.g. the following is a very valid use case (e.g. the user thinks the event passed in will be a more specific case of an event) and the type assertion works as expected:\n\n```ts\nfunction handler (event: Event) {\n    let mouseEvent = event as MouseEvent;\n}\n```\n\nHowever, the following is most likely an error and TypeScript will complain as shown despite the user's type assertion:\n\n```ts\nfunction handler(event: Event) {\n    let element = event as HTMLElement; // Error: Neither 'Event' nor type 'HTMLElement' is assignable to the other\n}\n```\n\nIf you *still want that Type, you can use a double assertion*, but first asserting to `unknown` (or `any`) which is compatible with all types and therefore the compiler no longer complains:\n\n```ts\nfunction handler(event: Event) {\n    let element = event as unknown as HTMLElement; // Okay!\n}\n```\n\n#### How TypeScript determines if a single assertion is not enough\nBasically, the assertion from type `S` to `T` succeeds if either `S` is a subtype of `T` or `T` is a subtype of `S`. This is to provide extra safety when doing type assertions ... completely wild assertions can be very unsafe and you need to use `unknown` (or `any`) to be that unsafe.\n\n#### `as any as` vs `as unknown as`\nBoth are *equally unsafe* as far as TypeScript is concerned. Use what makes you happy. Considerations: \n\n* Linters prefer `unknown` (with `no-explicit-any` rule)\n* `any` is less characters to type than `unknown`\n"
  },
  {
    "path": "docs/types/type-compatibility.md",
    "content": "* [Type Compatibility](#type-compatibility)\n* [Soundness](#soundness)\n* [Structural](#structural)\n* [Generics](#generics)\n* [Variance](#variance)\n* [Functions](#functions)\n  * [Return Type](#return-type)\n  * [Number of arguments](#number-of-arguments)\n  * [Optional and rest parameters](#optional-and-rest-parameters)\n  * [Types of arguments](#types-of-arguments)\n* [Enums](#enums)\n* [Classes](#classes)\n* [Generics](#generics)\n* [FootNote: Invariance](#footnote-invariance)\n\n## Type Compatibility\n\nType Compatibility (as we discuss here) determines if one thing can be assigned to another. E.g. `string` and `number` are not compatible:\n\n```ts\nlet str: string = \"Hello\";\nlet num: number = 123;\n\nstr = num; // ERROR: `number` is not assignable to `string`\nnum = str; // ERROR: `string` is not assignable to `number`\n```\n\n## Soundness\n\nTypeScript's type system is designed to be convenient and allows for *unsound* behaviours e.g. anything can be assigned to `any` which means telling the compiler to allow you to do whatever you want:\n\n```ts\nlet foo: any = 123;\nfoo = \"Hello\";\n\n// Later\nfoo.toPrecision(3); // Allowed as you typed it as `any`\n```\n\n## Structural\n\nTypeScript objects are structurally typed. This means the *names* don't matter as long as the structures match\n\n```ts\ninterface Point {\n    x: number,\n    y: number\n}\n\nclass Point2D {\n    constructor(public x:number, public y:number){}\n}\n\nlet p: Point;\n// OK, because of structural typing\np = new Point2D(1,2);\n```\n\nThis allows you to create objects on the fly (like you do in vanilla JS) and still have safety whenever it can be inferred.\n\nAlso *more* data is considered fine:\n\n```ts\ninterface Point2D {\n    x: number;\n    y: number;\n}\ninterface Point3D {\n    x: number;\n    y: number;\n    z: number;\n}\nvar point2D: Point2D = { x: 0, y: 10 }\nvar point3D: Point3D = { x: 0, y: 10, z: 20 }\nfunction iTakePoint2D(point: Point2D) { /* do something */ }\n\niTakePoint2D(point2D); // exact match okay\niTakePoint2D(point3D); // extra information okay\niTakePoint2D({ x: 0 }); // Error: missing information `y`\n```\n\n## Variance\n\nVariance is an easy to understand and important concept for type compatibility analysis.\n\nFor simple types `Base` and `Child`, if `Child` is a child of `Base`, then instances of `Child` can be assigned to a variable of type `Base`.\n\n> This is polymorphism 101\n\nIn type compatibility of complex types composed of such `Base` and `Child` types depends on where the `Base` and `Child` in similar scenarios is driven by *variance*.\n\n* Covariant : (co aka joint) only in *same direction*\n* Contravariant : (contra aka negative) only in *opposite direction*\n* Bivariant : (bi aka both) both co and contra.\n* Invariant : if the types aren't exactly the same then they are incompatible.\n\n> Note: For a completely sound type system in the presence of mutable data like JavaScript, `invariant` is the only valid option. But as mentioned *convenience* forces us to make unsound choices.\n\n## Functions\n\nThere are a few subtle things to consider when comparing two functions.\n\n### Return Type\n\n`covariant`: The return type must contain at least enough data.\n\n```ts\n/** Type Hierarchy */\ninterface Point2D { x: number; y: number; }\ninterface Point3D { x: number; y: number; z: number; }\n\n/** Two sample functions */\nlet iMakePoint2D = (): Point2D => ({ x: 0, y: 0 });\nlet iMakePoint3D = (): Point3D => ({ x: 0, y: 0, z: 0 });\n\n/** Assignment */\niMakePoint2D = iMakePoint3D; // Okay\niMakePoint3D = iMakePoint2D; // ERROR: Point2D is not assignable to Point3D\n```\n\n### Number of arguments\n\nFewer arguments are okay (i.e. functions can choose to ignore additional parameters). After all you are guaranteed to be called with at least enough arguments.\n\n```ts\nlet iTakeSomethingAndPassItAnErr\n    = (x: (err: Error, data: any) => void) => { /* do something */ };\n\niTakeSomethingAndPassItAnErr(() => null) // Okay\niTakeSomethingAndPassItAnErr((err) => null) // Okay\niTakeSomethingAndPassItAnErr((err, data) => null) // Okay\n\n// ERROR: Argument of type '(err: any, data: any, more: any) => null' is not assignable to parameter of type '(err: Error, data: any) => void'.\niTakeSomethingAndPassItAnErr((err, data, more) => null);\n```\n\n### Optional and Rest Parameters\n\nOptional (pre determined count) and Rest parameters (any count of arguments) are compatible, again for convenience.\n\n```ts\nlet foo = (x:number, y: number) => { /* do something */ }\nlet bar = (x?:number, y?: number) => { /* do something */ }\nlet bas = (...args: number[]) => { /* do something */ }\n\nfoo = bar = bas;\nbas = bar = foo;\n```\n\n> Note: optional (in our example `bar`) and non optional (in our example `foo`) are only compatible if strictNullChecks is false.\n\n### Types of arguments\n\n`bivariant` : This is designed to support common event handling scenarios\n\n```ts\n/** Event Hierarchy */\ninterface Event { timestamp: number; }\ninterface MouseEvent extends Event { x: number; y: number }\ninterface KeyEvent extends Event { keyCode: number }\n\n/** Sample event listener */\nenum EventType { Mouse, Keyboard }\nfunction addEventListener(eventType: EventType, handler: (n: Event) => void) {\n    /* ... */\n}\n\n// Unsound, but useful and common. Works as function argument comparison is bivariant\naddEventListener(EventType.Mouse, (e: MouseEvent) => console.log(e.x + \",\" + e.y));\n\n// Undesirable alternatives in presence of soundness\naddEventListener(EventType.Mouse, (e: Event) => console.log((<MouseEvent>e).x + \",\" + (<MouseEvent>e).y));\naddEventListener(EventType.Mouse, <(e: Event) => void>((e: MouseEvent) => console.log(e.x + \",\" + e.y)));\n\n// Still disallowed (clear error). Type safety enforced for wholly incompatible types\naddEventListener(EventType.Mouse, (e: number) => console.log(e));\n```\n\nAlso makes `Array<Child>` assignable to `Array<Base>` (covariance) as the functions are compatible. Array covariance requires all `Array<Child>` functions to be assignable to `Array<Base>` e.g. `push(t:Child)` is assignable to `push(t:Base)` which is made possible by function argument bivariance.\n\n**This can be confusing for people coming from other languages** who would expect the following to error but will not in TypeScript:\n\n```ts\n/** Type Hierarchy */\ninterface Point2D { x: number; y: number; }\ninterface Point3D { x: number; y: number; z: number; }\n\n/** Two sample functions */\nlet iTakePoint2D = (point: Point2D) => { /* do something */ }\nlet iTakePoint3D = (point: Point3D) => { /* do something */ }\n\niTakePoint3D = iTakePoint2D; // Okay : Reasonable\niTakePoint2D = iTakePoint3D; // Okay : WHAT\n```\n\n## Enums\n\n* Enums are compatible with numbers, and numbers are compatible with enums.\n\n```ts\nenum Status { Ready, Waiting };\n\nlet status = Status.Ready;\nlet num = 0;\n\nstatus = num; // OKAY\nnum = status; // OKAY\n```\n\n* Enum values from different enum types are considered incompatible. This makes enums useable *nominally* (as opposed to structurally)\n\n```ts\nenum Status { Ready, Waiting };\nenum Color { Red, Blue, Green };\n\nlet status = Status.Ready;\nlet color = Color.Red;\n\nstatus = color; // ERROR\n```\n\n## Classes\n\n* Only instance members and methods are compared. *constructors* and *statics* play no part.\n\n```ts\nclass Animal {\n    feet: number;\n    constructor(name: string, numFeet: number) { /** do something */ }\n}\n\nclass Size {\n    feet: number;\n    constructor(meters: number) { /** do something */ }\n}\n\nlet a: Animal;\nlet s: Size;\n\na = s;  // OK\ns = a;  // OK\n```\n\n* `private` and `protected` members *must originate from the same class*. Such members essentially make the class *nominal*.\n\n```ts\n/** A class hierarchy */\nclass Animal { protected feet: number; }\nclass Cat extends Animal { }\n\nlet animal: Animal;\nlet cat: Cat;\n\nanimal = cat; // OKAY\ncat = animal; // OKAY\n\n/** Looks just like Animal */\nclass Size { protected feet: number; }\n\nlet size: Size;\n\nanimal = size; // ERROR\nsize = animal; // ERROR\n```\n\n## Generics\n\nSince TypeScript has a structural type system, type parameters only affect compatibility when used by a member. For example, in the  following `T` has no impact on compatibility:\n\n```ts\ninterface Empty<T> {\n}\nlet x: Empty<number>;\nlet y: Empty<string>;\n\nx = y;  // okay, y matches structure of x\n```\n\nHowever, if `T` is used, it will play a role in compatibility based on its *instantiation* as shown below:\n\n```ts\ninterface NotEmpty<T> {\n    data: T;\n}\nlet x: NotEmpty<number>;\nlet y: NotEmpty<string>;\n\nx = y;  // error, x and y are not compatible\n```\n\nIn cases where generic arguments haven't been *instantiated* they are substituted by `any` before checking compatibility:\n\n```ts\nlet identity = function<T>(x: T): T {\n    // ...\n}\n\nlet reverse = function<U>(y: U): U {\n    // ...\n}\n\nidentity = reverse;  // Okay because (x: any)=>any matches (y: any)=>any\n```\n\nGenerics involving classes are matched by relevant class compatibility as mentioned before. e.g. \n\n```ts\nclass List<T> {\n  add(val: T) { }\n}\n\nclass Animal { name: string; }\nclass Cat extends Animal { meow() { } }\n\nconst animals = new List<Animal>();\nanimals.add(new Animal()); // Okay \nanimals.add(new Cat()); // Okay \n\nconst cats = new List<Cat>();\ncats.add(new Animal()); // Error \ncats.add(new Cat()); // Okay\n```\n\n## FootNote: Invariance\n\nWe said invariance is the only sound option. Here is an example where both `contra` and `co` variance are shown to be unsafe for arrays.\n\n```ts\n/** Hierarchy */\nclass Animal { constructor(public name: string){} }\nclass Cat extends Animal { meow() { } }\n\n/** An item of each */\nvar animal = new Animal(\"animal\");\nvar cat = new Cat(\"cat\");\n\n/**\n * Demo : polymorphism 101\n * Animal <= Cat\n */\nanimal = cat; // Okay\ncat = animal; // ERROR: cat extends animal\n\n/** Array of each to demonstrate variance */\nlet animalArr: Animal[] = [animal];\nlet catArr: Cat[] = [cat];\n\n/**\n * Obviously Bad : Contravariance\n * Animal <= Cat\n * Animal[] >= Cat[]\n */\ncatArr = animalArr; // Okay if contravariant\ncatArr[0].meow(); // Allowed but BANG 🔫 at runtime\n\n\n/**\n * Also Bad : covariance\n * Animal <= Cat\n * Animal[] <= Cat[]\n */\nanimalArr = catArr; // Okay if covariant\nanimalArr.push(new Animal('another animal')); // Just pushed an animal into catArr!\ncatArr.forEach(c => c.meow()); // Allowed but BANG 🔫 at runtime\n```\n"
  },
  {
    "path": "docs/types/type-inference.md",
    "content": "# Type Inference in TypeScript\n\nTypeScript can infer (and then check) the type of a variable based on a few simple rules. Because these rules\nare simple you can train your brain to recognize safe / unsafe code (it happened for me and my teammates quite quickly).\n\n> The types flowing is just how I imagine in my brain the flow of type information.\n\n## Variable Definition\n\nTypes of a variable are inferred by definition.\n\n```ts\nlet foo = 123; // foo is a `number`\nlet bar = \"Hello\"; // bar is a `string`\nfoo = bar; // Error: cannot assign `string` to a `number`\n```\n\nThis is an example of types flowing from right to left.\n\n## Function Return Types\n\nThe return type is inferred by the return statements e.g. the following function is inferred to return a `number`.\n\n```ts\nfunction add(a: number, b: number) {\n    return a + b;\n}\n```\n\nThis is an example of types flowing bottom out.\n\n## Assignment\n\nThe type of function parameters / return values can also be inferred by assignment e.g. here we say that `foo` is an `Adder`, that makes `number` the type of `a` and `b`.\n\n```ts\ntype Adder = (a: number, b: number) => number;\nlet foo: Adder = (a, b) => a + b;\n```\n\nThis fact can be demonstrated by the below code which raises an error as you would hope:\n\n```ts\ntype Adder = (a: number, b: number) => number;\nlet foo: Adder = (a, b) => {\n    a = \"hello\"; // Error: cannot assign `string` to a `number`\n    return a + b;\n}\n```\n\nThis is an example of types flowing from left to right.\n\nThe same *assignment* style type inference works if you create a function for a callback argument. After all an `argument -> parameter`is just another form of variable assignment.\n\n```ts\ntype Adder = (a: number, b: number) => number;\nfunction iTakeAnAdder(adder: Adder) {\n    return adder(1, 2);\n}\niTakeAnAdder((a, b) => {\n    // a = \"hello\"; // Would Error: cannot assign `string` to a `number`\n    return a + b;\n})\n```\n\n## Structuring\n\nThese simple rules also work in the presence of **structuring** (object literal creation). For example in the following case the type of `foo` is inferred to be `{a:number, b:number}`\n\n```ts\nlet foo = {\n    a: 123,\n    b: 456\n};\n// foo.a = \"hello\"; // Would Error: cannot assign `string` to a `number`\n```\n\nSimilarly for arrays:\n\n```ts\nconst bar = [1,2,3];\n// bar[0] = \"hello\"; // Would error: cannot assign `string` to a `number`\n```\n\nAnd of course any nesting:\n\n```ts\nlet foo = {\n    bar: [1, 3, 4]\n};\n// foo.bar[0] = 'hello'; // Would error: cannot assign `string` to a `number`\n```\n\n## Destructuring\n\nAnd of course, they also work with destructuring, both objects:\n\n```ts\nlet foo = {\n    a: 123,\n    b: 456\n};\nlet {a} = foo;\n// a = \"hello\"; // Would Error: cannot assign `string` to a `number`\n```\n\nand arrays:\n\n```ts\nconst bar = [1, 2];\nlet [a, b] = bar;\n// a = \"hello\"; // Would Error: cannot assign `string` to a `number`\n```\n\nAnd if the function parameter can be inferred, so can its destructured properties. For example here we destructure the argument into its `a`/`b` members.\n\n```ts\ntype Adder = (numbers: { a: number, b: number }) => number;\nfunction iTakeAnAdder(adder: Adder) {\n    return adder({ a: 1, b: 2 });\n}\niTakeAnAdder(({a, b}) => { // Types of `a` and `b` are inferred\n    // a = \"hello\"; // Would Error: cannot assign `string` to a `number`\n    return a + b;\n})\n```\n\n## Type Guards\n\nWe have already seen how [Type Guards](./typeGuard.md) help change and narrow down types (particularly in the case of unions). Type guards are just another form of type inference for a variable in a block.\n\n## Warnings\n\n### Be careful around parameters\n\nTypes do not flow into the function parameters if it cannot be inferred from an assignment. For example in the following case the compiler does not know the type of `foo` so it cannot infer the type of `a` or `b`.\n\n```ts\nconst foo = (a,b) => { /* do something */ };\n```\n\nHowever, if `foo` was typed the function parameters type can be inferred (`a`,`b` are both inferred to be of type `number` in the example below).\n\n```ts\ntype TwoNumberFunction = (a: number, b: number) => void;\nconst foo: TwoNumberFunction = (a, b) => { /* do something */ };\n```\n\n### Be careful around return\n\nAlthough TypeScript can generally infer the return type of a function, it might not be what you expect. For example here function `foo` has a return type of `any`.\n\n```ts\nfunction foo(a: number, b: number) {\n    return a + addOne(b);\n}\n// Some external function in a library someone wrote in JavaScript\nfunction addOne(c) {\n    return c + 1;\n}\n```\n\nThis is because the return type is impacted by the poor type definition for `addOne` (`c` is `any` so the return of `addOne` is `any` so the return of `foo` is `any`).\n\n> I find it simplest to always be explicit about function returns. After all, these annotations are a theorem and the function body is the proof.\n\nThere are other cases that one can imagine, but the good news is that there is a compiler flag that can help catch such bugs.\n\n## `noImplicitAny`\n\nThe flag `noImplicitAny` instructs the compiler to raise an error if it cannot infer the type of a variable (and therefore can only have it as an *implicit* `any` type). You can then\n\n* either say that *yes I want it to be of type `any`* by *explicitly* adding an `: any` type annotation\n* help the compiler out by adding a few more *correct* annotations.\n"
  },
  {
    "path": "docs/types/type-system.md",
    "content": "# TypeScript Type System\nWe covered the main features of the TypeScript Type System back when we discussed [Why TypeScript?](../why-typescript.md). The following are a few key takeaways from that discussion which don't need further explanation:\n* The type system in TypeScript is designed to be *optional* so that *your JavaScript is TypeScript*.\n* TypeScript does not block *JavaScript emit* in the presence of Type Errors, allowing you to *progressively update your JS to TS*.\n\nNow let's start with the *syntax* of the TypeScript type system. This way you can start using these annotations in your code immediately and see the benefit. This will prepare you for a deeper dive later.\n\n## Basic Annotations\nAs mentioned before Types are annotated using `:TypeAnnotation` syntax. Anything that is available in the type declaration space can be used as a Type Annotation.\n\nThe following example demonstrates type annotations for variables, function parameters and function return values:\n\n```ts\nvar num: number = 123;\nfunction identity(num: number): number {\n    return num;\n}\n```\n\n### Primitive Types\nThe JavaScript primitive types are well represented in the TypeScript type system. This means `string`, `number`, `boolean` as demonstrated below:\n\n```ts\nvar num: number;\nvar str: string;\nvar bool: boolean;\n\nnum = 123;\nnum = 123.456;\nnum = '123'; // Error\n\nstr = '123';\nstr = 123; // Error\n\nbool = true;\nbool = false;\nbool = 'false'; // Error\n```\n\n### Arrays\nTypeScript provides dedicated type syntax for arrays to make it easier for you to annotate and document your code. The syntax is basically postfixing `[]` to any valid type annotation (e.g. `:boolean[]`). It allows you to safely do any array manipulation that you would normally do and protects you from errors like assigning a member of the wrong type.  This is demonstrated below:\n\n```ts\nvar boolArray: boolean[];\n\nboolArray = [true, false];\nconsole.log(boolArray[0]); // true\nconsole.log(boolArray.length); // 2\nboolArray[1] = true;\nboolArray = [false, false];\n\nboolArray[0] = 'false'; // Error!\nboolArray = 'false'; // Error!\nboolArray = [true, 'false']; // Error!\n```\n\n### Interfaces\nInterfaces are the core way in TypeScript to compose multiple type annotations into a single named annotation. Consider the following example:\n\n```ts\ninterface Name {\n    first: string;\n    second: string;\n}\n\nvar name: Name;\nname = {\n    first: 'John',\n    second: 'Doe'\n};\n\nname = {           // Error : `second` is missing\n    first: 'John'\n};\nname = {           // Error : `second` is the wrong type\n    first: 'John',\n    second: 1337\n};\n```\n\nHere we've composed the annotations `first: string` + `second: string` into a new annotation `Name` that enforces the type checks on individual members. Interfaces have a lot of power in TypeScript and we will dedicate an entire section to how you can use that to your advantage.\n\n### Inline Type Annotation\nInstead of creating a new `interface` you can annotate anything you want *inline* using `:{ /*Structure*/ }`. The previous example presented again with an inline type:\n\n```ts\nvar name: {\n    first: string;\n    second: string;\n};\nname = {\n    first: 'John',\n    second: 'Doe'\n};\n\nname = {           // Error : `second` is missing\n    first: 'John'\n};\nname = {           // Error : `second` is the wrong type\n    first: 'John',\n    second: 1337\n};\n```\n\nInline types are great for quickly providing a one off type annotation for something. It saves you the hassle of coming up with (a potentially bad) type name. However, if you find yourself putting in the same type annotation inline multiple times it's a good idea to consider refactoring it into an interface (or a `type alias` covered later in this section).\n\n## Special Types\nBeyond the primitive types that have been covered there are a few types that have special meaning in TypeScript. These are `any`, `null`, `undefined`, `void`.\n\n### any\nThe `any` type holds a special place in the TypeScript type system. It gives you an escape hatch from the type system to tell the compiler to bugger off. `any` is compatible with *any and all* types in the type system. This means that *anything can be assigned to it* and *it can be assigned to anything*. This is demonstrated in the example below:\n\n```ts\nvar power: any;\n\n// Takes any and all types\npower = '123';\npower = 123;\n\n// Is compatible with all types\nvar num: number;\npower = num;\nnum = power;\n```\n\nIf you are porting JavaScript code to TypeScript, you are going to be close friends with `any` in the beginning. However, don't take this friendship too seriously as it means that *it is up to you to ensure the type safety*. You are basically telling the compiler to *not do any meaningful static analysis*.\n\n### `null` and `undefined`\n\nHow they are treated by the type system depends on the `strictNullChecks` compiler flag (we cover this flag later). When in `strictNullCheck:false`, the `null` and `undefined` JavaScript literals are effectively treated by the type system the same as something of type `any`. These literals can be assigned to any other type. This is demonstrated in the below example:\n\n```ts\nvar num: number;\nvar str: string;\n\n// These literals can be assigned to anything\nnum = null;\nstr = undefined;\n```\n\n### `:void`\nUse `:void` to signify that a function does not have a return type:\n\n```ts\nfunction log(message): void {\n    console.log(message);\n}\n```\n\n## Generics\nMany algorithms and data structures in computer science do not depend on the *actual type* of the object. However, you still want to enforce a constraint between various variables. A simple toy example is a function that takes a list of items and returns a reversed list of items. The constraint here is between what is passed in to the function and what is returned by the function:\n\n```ts\nfunction reverse<T>(items: T[]): T[] {\n    var toreturn = [];\n    for (let i = items.length - 1; i >= 0; i--) {\n        toreturn.push(items[i]);\n    }\n    return toreturn;\n}\n\nvar sample = [1, 2, 3];\nvar reversed = reverse(sample);\nconsole.log(reversed); // 3,2,1\n\n// Safety!\nreversed[0] = '1';     // Error!\nreversed = ['1', '2']; // Error!\n\nreversed[0] = 1;       // Okay\nreversed = [1, 2];     // Okay\n```\n\nHere you are basically saying that the function `reverse` takes an array (`items: T[]`) of *some* type `T` (notice the type parameter in `reverse<T>`) and returns an array of type `T` (notice `: T[]`). Because the `reverse` function returns items of the same type as it takes, TypeScript knows the `reversed` variable is also of type `number[]` and will give you Type safety. Similarly if you pass in an array of `string[]` to the reverse function the returned result is also an array of `string[]` and you get similar type safety as shown below:\n\n```ts\nvar strArr = ['1', '2'];\nvar reversedStrs = reverse(strArr);\n\nreversedStrs = [1, 2]; // Error!\n```\n\nIn fact JavaScript arrays already have a `.reverse` function and TypeScript does indeed use generics to define its structure:\n\n```ts\ninterface Array<T> {\n reverse(): T[];\n // ...\n}\n```\n\nThis means that you get type safety when calling `.reverse` on any array as shown below:\n\n```ts\nvar numArr = [1, 2];\nvar reversedNums = numArr.reverse();\n\nreversedNums = ['1', '2']; // Error!\n```\n\nWe will discuss more about the `Array<T>` interface later when we present `lib.d.ts` in the section **Ambient Declarations**.\n\n## Union Type\nQuite commonly in JavaScript you want to allow a property to be one of multiple types e.g. *a `string` or a `number`*. This is where the *union type* (denoted by `|` in a type annotation e.g. `string|number`) comes in handy. A common use case is a function that can take a single object or an array of the object e.g.:\n\n```ts\nfunction formatCommandline(command: string[]|string) {\n    var line = '';\n    if (typeof command === 'string') {\n        line = command.trim();\n    } else {\n        line = command.join(' ').trim();\n    }\n\n    // Do stuff with line: string\n}\n```\n\n## Intersection Type\n`extend` is a very common pattern in JavaScript where you take two objects and create a new one that has the features of both these objects. An **Intersection Type** allows you to use this pattern in a safe way as demonstrated below:\n\n```ts\nfunction extend<T, U>(first: T, second: U): T & U {\n  return { ...first, ...second };\n}\n\nconst x = extend({ a: \"hello\" }, { b: 42 });\n\n// x now has both `a` and `b`\nconst a = x.a;\nconst b = x.b;\n```\n\n## Tuple Type\nJavaScript doesn't have first class tuple support. People generally just use an array as a tuple. This is exactly what the TypeScript type system supports. Tuples can be annotated using `: [typeofmember1, typeofmember2]` etc. A tuple can have any number of members. Tuples are demonstrated in the below example:\n\n```ts\nvar nameNumber: [string, number];\n\n// Okay\nnameNumber = ['Jenny', 8675309];\n\n// Error!\nnameNumber = ['Jenny', '867-5309'];\n```\n\nCombine this with the destructuring support in TypeScript, tuples feel fairly first class despite being arrays underneath:\n\n```ts\nvar nameNumber: [string, number];\nnameNumber = ['Jenny', 8675309];\n\nvar [name, num] = nameNumber;\n```\n\n## Type Alias\nTypeScript provides convenient syntax for providing names for type annotations that you would like to use in more than one place. The aliases are created using the `type SomeName = someValidTypeAnnotation` syntax. An example is demonstrated below:\n\n```ts\ntype StrOrNum = string|number;\n\n// Usage: just like any other notation\nvar sample: StrOrNum;\nsample = 123;\nsample = '123';\n\n// Just checking\nsample = true; // Error!\n```\n\nUnlike an `interface` you can give a type alias to literally any type annotation (useful for stuff like union and intersection types). Here are a few more examples to make you familiar with the syntax:\n\n```ts\ntype Text = string | { text: string };\ntype Coordinates = [number, number];\ntype Callback = (data: string) => void;\n```\n\n> TIP: If you need to have hierarchies of Type annotations use an `interface`. They can be used with `implements` and `extends`\n\n> TIP: Use a type alias for simpler object structures (like `Coordinates`) just to give them a semantic name. Also when you want to give semantic names to Union or Intersection types, a Type alias is the way to go.\n\n## Summary\nNow that you can start annotating most of your JavaScript code we can jump into the nitty gritty details of all the power available in TypeScript's Type System.\n"
  },
  {
    "path": "docs/types/typeGuard.md",
    "content": "* [Type Guard](#type-guard)\n* [User Defined Type Guards](#user-defined-type-guards)\n\n## Type Guard\nType Guards allow you to narrow down the type of an object within a conditional block. \n\n\n### typeof\n\nTypeScript is aware of the usage of the JavaScript `instanceof` and `typeof` operators. If you use these in a conditional block, TypeScript will understand the type of the variable to be different within that conditional block. Here is a quick example where TypeScript realizes that a particular function does not exist on `string` and points out what was probably a user typo:\n\n```ts\nfunction doSomething(x: number | string) {\n    if (typeof x === 'string') { // Within the block TypeScript knows that `x` must be a string\n        console.log(x.subtr(1)); // Error, 'subtr' does not exist on `string`\n        console.log(x.substr(1)); // OK\n    }\n    x.substr(1); // Error: There is no guarantee that `x` is a `string`\n}\n```\n\n### instanceof\n\nHere is an example with a class and `instanceof`:\n\n```ts\nclass Foo {\n    foo = 123;\n    common = '123';\n}\n\nclass Bar {\n    bar = 123;\n    common = '123';\n}\n\nfunction doStuff(arg: Foo | Bar) {\n    if (arg instanceof Foo) {\n        console.log(arg.foo); // OK\n        console.log(arg.bar); // Error!\n    }\n    if (arg instanceof Bar) {\n        console.log(arg.foo); // Error!\n        console.log(arg.bar); // OK\n    }\n\n    console.log(arg.common); // OK\n    console.log(arg.foo); // Error!\n    console.log(arg.bar); // Error!\n}\n\ndoStuff(new Foo());\ndoStuff(new Bar());\n```\n\nTypeScript even understands `else` so when an `if` narrows out one type it knows that within the else *it's definitely not that type*. Here is an example:\n\n```ts\nclass Foo {\n    foo = 123;\n}\n\nclass Bar {\n    bar = 123;\n}\n\nfunction doStuff(arg: Foo | Bar) {\n    if (arg instanceof Foo) {\n        console.log(arg.foo); // OK\n        console.log(arg.bar); // Error!\n    }\n    else {  // MUST BE Bar!\n        console.log(arg.foo); // Error!\n        console.log(arg.bar); // OK\n    }\n}\n\ndoStuff(new Foo());\ndoStuff(new Bar());\n```\n\n### in \n\nThe `in` operator does a safe check for the existence of a property on an object and can be used as a type guard. E.g. \n\n```ts\ninterface A {\n  x: number;\n}\ninterface B {\n  y: string;\n}\n\nfunction doStuff(q: A | B) {\n  if ('x' in q) {\n    // q: A\n  }\n  else {\n    // q: B\n  }\n}\n```\n\n### Literal Type Guard\n\nYou can use `===` / `==` / `!==` / `!=` to distinguish between literal values\n\n```ts\ntype TriState = 'yes' | 'no' | 'unknown';\n\nfunction logOutState(state:TriState) {\n  if (state == 'yes') {\n    console.log('User selected yes');\n  } else if (state == 'no') {\n    console.log('User selected no');\n  } else {\n    console.log('User has not made a selection yet');\n  }\n}\n```\n\nThis even works when you have literal types in a union. You can check the value of a shared property name to discriminate the union e.g. \n\n```ts\ntype Foo = {\n  kind: 'foo', // Literal type \n  foo: number\n}\ntype Bar = {\n  kind: 'bar', // Literal type \n  bar: number\n}\n\nfunction doStuff(arg: Foo | Bar) {\n    if (arg.kind === 'foo') {\n        console.log(arg.foo); // OK\n        console.log(arg.bar); // Error!\n    }\n    else {  // MUST BE Bar!\n        console.log(arg.foo); // Error!\n        console.log(arg.bar); // OK\n    }\n}\n```\n\n### null and undefined with `strictNullChecks`\n\nTypeScript is smart enough to rule out both `null` and `undefined` with a `== null` / `!= null` check. For example:\n\n```ts\nfunction foo(a?: number | null) {\n  if (a == null) return;\n\n  // a is number now.\n}\n```\n\n### User Defined Type Guards\nJavaScript doesn't have very rich runtime introspection support built in. When you are using just plain JavaScript Objects (using structural typing to your advantage), you do not even have access to `instanceof` or `typeof`. For these cases you can create *User Defined Type Guard functions*. These are just functions that return `someArgumentName is SomeType`. Here is an example:\n\n```ts\n/**\n * Just some interfaces\n */\ninterface Foo {\n    foo: number;\n    common: string;\n}\n\ninterface Bar {\n    bar: number;\n    common: string;\n}\n\n/**\n * User Defined Type Guard!\n */\nfunction isFoo(arg: any): arg is Foo {\n    return arg.foo !== undefined;\n}\n\n/**\n * Sample usage of the User Defined Type Guard\n */\nfunction doStuff(arg: Foo | Bar) {\n    if (isFoo(arg)) {\n        console.log(arg.foo); // OK\n        console.log(arg.bar); // Error!\n    }\n    else {\n        console.log(arg.foo); // Error!\n        console.log(arg.bar); // OK\n    }\n}\n\ndoStuff({ foo: 123, common: '123' });\ndoStuff({ bar: 123, common: '123' });\n```\n\n### Type Guards and callbacks\n\nTypeScript doesn't assume type guards remain active in callbacks as making this assumption is dangerous. e.g. \n\n```js\n// Example Setup\ndeclare var foo:{bar?: {baz: string}};\nfunction immediate(callback: ()=>void) {\n  callback();\n}\n\n\n// Type Guard\nif (foo.bar) {\n  console.log(foo.bar.baz); // Okay\n  functionDoingSomeStuff(() => {\n    console.log(foo.bar.baz); // TS error: Object is possibly 'undefined'\"\n  });\n}\n```\n\nThe fix is as easy as storing the inferred safe value in a local variable, automatically ensuring it doesn't get changed externally, and TypeScript can easily understand that: \n\n```js\n// Type Guard\nif (foo.bar) {\n  console.log(foo.bar.baz); // Okay\n  const bar = foo.bar;\n  functionDoingSomeStuff(() => {\n    console.log(bar.baz); // Okay\n  });\n}\n```\n"
  },
  {
    "path": "docs/why-typescript.md",
    "content": "# Why TypeScript\nThere are two main goals of TypeScript:\n* Provide an *optional type system* for JavaScript.\n* Provide planned features from future JavaScript editions to current JavaScript engines\n\nThe desire for these goals is motivated below.\n\n## The TypeScript type system\n\nYou might be wondering \"**Why add types to JavaScript?**\"\n\nTypes have proven ability to enhance code quality and understandability. Large teams (Google, Microsoft, Facebook) have continually arrived at this conclusion. Specifically:\n\n* Types increase your agility when doing refactoring. *It's better for the compiler to catch errors than to have things fail at runtime*.\n* Types are one of the best forms of documentation you can have. *The function signature is a theorem and the function body is the proof*.\n\nHowever, types have a way of being unnecessarily ceremonious. TypeScript is very particular about keeping the barrier to entry as low as possible. Here's how:\n\n### Your JavaScript is TypeScript\nTypeScript provides compile time type safety for your JavaScript code. This is no surprise given its name. The great thing is that the types are completely optional. Your JavaScript code `.js` file can be renamed to a `.ts` file and TypeScript will still give you back valid `.js` equivalent to the original JavaScript file. TypeScript is *intentionally* and strictly a superset of JavaScript with optional Type checking.\n\n### Types can be Implicit\nTypeScript will try to infer as much of the type information as it can in order to give you type safety with minimal cost of productivity during code development. For example, in the following example TypeScript will know that foo is of type `number` below and will give an error on the second line as shown:\n\n```ts\nvar foo = 123;\nfoo = '456'; // Error: cannot assign `string` to `number`\n\n// Is foo a number or a string?\n```\nThis type inference is well motivated. If you do stuff like shown in this example, then, in the rest of your code, you cannot be certain that `foo` is a `number` or a `string`. Such issues turn up often in large multi-file code bases. We will deep dive into the type inference rules later.\n\n### Types can be Explicit\nAs we've mentioned before, TypeScript will infer as much as it can safely. However, you can use annotations to:\n\n1. Help along the compiler, and more importantly document stuff for the next developer who has to read your code (that might be future you!).\n1. Enforce that what the compiler sees, is what you thought it should see. That is your understanding of the code matches an algorithmic analysis of the code (done by the compiler).\n\nTypeScript uses postfix type annotations popular in other *optionally* annotated languages (e.g. ActionScript and F#).\n\n```ts\nvar foo: number = 123;\n```\nSo if you do something wrong the compiler will report an error e.g.:\n\n```ts\nvar foo: number = '123'; // Error: cannot assign a `string` to a `number`\n```\n\nWe will discuss all the details of all the annotation syntax supported by TypeScript in a later chapter.\n\n### Types are structural\nIn some languages (specifically nominally typed ones) static typing results in unnecessary ceremony because even though *you know* that the code will work fine the language semantics force you to copy stuff around. This is why stuff like [automapper for C#](http://automapper.org/) is *vital* for C#. In TypeScript because we really want it to be easy for JavaScript developers with a minimum cognitive overload, types are *structural*. This means that *duck typing* is a first class language construct. Consider the following example. The function `iTakePoint2D` will accept anything that contains all the things (`x` and `y`) it expects:\n\n```ts\ninterface Point2D {\n    x: number;\n    y: number;\n}\ninterface Point3D {\n    x: number;\n    y: number;\n    z: number;\n}\nvar point2D: Point2D = { x: 0, y: 10 }\nvar point3D: Point3D = { x: 0, y: 10, z: 20 }\nfunction iTakePoint2D(point: Point2D) { /* do something */ }\n\niTakePoint2D(point2D); // exact match okay\niTakePoint2D(point3D); // extra information okay\niTakePoint2D({ x: 0 }); // Error: missing information `y`\n```\n\n### Type errors do not prevent JavaScript emit\nTo make it easy for you to migrate your JavaScript code to TypeScript, even if there are compilation errors, by default TypeScript *will emit valid JavaScript* the best that it can. e.g.\n\n```ts\nvar foo = 123;\nfoo = '456'; // Error: cannot assign a `string` to a `number`\n```\n\nwill emit the following js:\n\n```ts\nvar foo = 123;\nfoo = '456';\n```\n\nSo you can incrementally upgrade your JavaScript code to TypeScript. This is very different from how many other language compilers work and yet another reason to move to TypeScript.\n\n### Types can be ambient\nA major design goal of TypeScript was to make it possible for you to safely and easily use existing JavaScript libraries in TypeScript. TypeScript does this by means of *declaration*. TypeScript provides you with a sliding scale of how much or how little effort you want to put in your declarations, the more effort you put the more type safety + code intelligence you get. Note that definitions for most of the popular JavaScript libraries have already been written for you by the [DefinitelyTyped community](https://github.com/borisyankov/DefinitelyTyped) so for most purposes either:\n\n1. The definition file already exists.\n1. Or at the very least, you have a vast list of well reviewed TypeScript declaration templates already available\n\nAs a quick example of how you would author your own declaration file, consider a trivial example of [jquery](https://jquery.com/). By default (as is to be expected of good JS code) TypeScript expects you to declare (i.e. use `var` somewhere) before you use a variable\n```ts\n$('.awesome').show(); // Error: cannot find name `$`\n```\nAs a quick fix *you can tell TypeScript* that there is indeed something called `$`:\n```ts\ndeclare var $: any;\n$('.awesome').show(); // Okay!\n```\nIf you want you can build on this basic definition and provide more information to help protect you from errors:\n```ts\ndeclare var $: {\n    (selector:string): any;\n};\n$('.awesome').show(); // Okay!\n$(123).show(); // Error: selector needs to be a string\n```\n\nWe will discuss the details of creating TypeScript definitions for existing JavaScript in detail later once you know more about TypeScript (e.g. stuff like `interface` and the `any`).\n\n## Future JavaScript => Now\nTypeScript provides a number of features that are planned in ES6 for current JavaScript engines (that only support ES5 etc). The TypeScript team is actively adding these features and this list is only going to get bigger over time and we will cover this in its own section. But just as a specimen here is an example of a class:\n\n```ts\nclass Point {\n    constructor(public x: number, public y: number) {\n    }\n    add(point: Point) {\n        return new Point(this.x + point.x, this.y + point.y);\n    }\n}\n\nvar p1 = new Point(0, 10);\nvar p2 = new Point(10, 20);\nvar p3 = p1.add(p2); // { x: 10, y: 30 }\n```\n\nand the lovely fat arrow function:\n\n```ts\nvar inc = x => x+1;\n```\n\n### Summary\nIn this section we have provided you with the motivation and design goals of TypeScript. With this out of the way we can dig into the nitty gritty details of TypeScript.\n\n[](Interfaces are open ended)\n[](Type Inference rules)\n[](Cover all the annotations)\n[](Cover all ambients : also that there are no runtime enforcement)\n[](.ts vs. .d.ts)\n"
  },
  {
    "path": "footer.md",
    "content": "[![fork me](/images/github.png) Fork me on github](https://github.com/basarat/typescript-book/)\n"
  },
  {
    "path": "header.html",
    "content": "<script>\n  function __addSupport() {\n    var el = document.querySelector('.search-noresults');\n      var content = '<a href=\"https://paypal.me/basaratali\" style=\"display: block;text-align: center;\"> Buy me a beer / coffee 🍻 ☕️ 🌹 <br><br><img src=\"https://img.shields.io/badge/Donate-PayPal-green.svg\" alt=\"donate\"><br><br></a>';\n      if(el) {\n        if (el.innerHTML.indexOf(content) === -1){\n          var elChild = document.createElement('div');\n          elChild.innerHTML = content;\n          el.insertBefore(elChild, el.firstChild);\n        }\n        clearInterval(interval);\n     }\n  }\n  __addSupport();\n  var interval = setInterval(function(){\n     __addSupport(); \n  },1000);\n</script>\n"
  },
  {
    "path": "snippets/md-snippets.cson",
    "content": "'.source.gfm':\n    'include':\n        'prefix': 'include'\n        'body': \"\"\"\n            {% include \"${1:./path}.md\" %}            \n        \"\"\""
  }
]