Full Code of basarat/typescript-book for AI

master e31fe92c3afe cached
261 files
627.9 KB
164.3k tokens
397 symbols
1 requests
Download .txt
Showing preview only (685K chars total). Download the full file or copy to clipboard to get everything.
Repository: basarat/typescript-book
Branch: master
Commit: e31fe92c3afe
Files: 261
Total size: 627.9 KB

Directory structure:
gitextract_d86sgzr5/

├── .gitattributes
├── .github/
│   └── workflows/
│       └── build.yml
├── .gitignore
├── CONTRIBUTING.md
├── GLOSSARY.md
├── LICENSE.md
├── README.md
├── SUMMARY.md
├── book.json
├── code/
│   ├── async-await/
│   │   ├── es5/
│   │   │   ├── asyncAwaitES5.js
│   │   │   ├── asyncAwaitES5.ts
│   │   │   └── tsconfig.json
│   │   └── es6/
│   │       ├── asyncAwaitES6.js
│   │       ├── asyncAwaitES6.ts
│   │       └── tsconfig.json
│   ├── compiler/
│   │   ├── package.json
│   │   ├── parser/
│   │   │   ├── runParser.js
│   │   │   └── runParser.ts
│   │   ├── scanner/
│   │   │   ├── runScanner.js
│   │   │   ├── runScanner.ts
│   │   │   ├── runScannerWithPositions.js
│   │   │   └── runScannerWithPositions.ts
│   │   ├── tsconfig.json
│   │   ├── tsd.json
│   │   └── typings/
│   │       ├── node/
│   │       │   └── node.d.ts
│   │       └── tsd.d.ts
│   ├── declarationspaces/
│   │   ├── declarationspace.js
│   │   └── declarationspace.ts
│   ├── dynamic-import-expressions/
│   │   ├── dynamicImportExpression.js
│   │   ├── dynamicImportExpression.ts
│   │   ├── package.json
│   │   └── tsconfig.json
│   ├── errors/
│   │   ├── common-errors.ts
│   │   ├── interpreting-errors.ts
│   │   └── tsconfig.json
│   ├── es6/
│   │   ├── classes/
│   │   │   ├── abstract.js
│   │   │   ├── abstract.ts
│   │   │   ├── class.js
│   │   │   ├── class.ts
│   │   │   ├── super.js
│   │   │   ├── super.ts
│   │   │   └── tsconfig.json
│   │   ├── const.js
│   │   ├── const.ts
│   │   ├── destructuring.js
│   │   ├── destructuring.ts
│   │   ├── enums.js
│   │   ├── enums.ts
│   │   ├── for..of.js
│   │   ├── for..of.ts
│   │   ├── forof.js
│   │   ├── iterators.js
│   │   ├── iterators.ts
│   │   ├── let.js
│   │   ├── let.ts
│   │   ├── rest-parameters.js
│   │   ├── rest-parameters.ts
│   │   ├── spread-operator.js
│   │   ├── spread-operator.ts
│   │   ├── template-strings.js
│   │   ├── template-strings.ts
│   │   ├── test.js
│   │   ├── test.ts
│   │   └── tsconfig.json
│   ├── javascript/
│   │   ├── closure.js
│   │   ├── closure.ts
│   │   └── tsconfig.json
│   ├── tips/
│   │   ├── bindIsBad.js
│   │   ├── bindIsBad.ts
│   │   ├── currying.js
│   │   ├── currying.ts
│   │   ├── lazyObjectLiteralInitialization.js
│   │   ├── lazyObjectLiteralInitialization.ts
│   │   ├── mixins.js
│   │   ├── mixins.ts
│   │   ├── nominalTyping.js
│   │   ├── nominalTyping.ts
│   │   ├── statefulFunctions.js
│   │   ├── statefulFunctions.ts
│   │   ├── stringEnums.js
│   │   ├── stringEnums.ts
│   │   └── tsconfig.json
│   └── types/
│       ├── assertion.js
│       ├── assertion.ts
│       ├── callable.ts
│       ├── freshness/
│       │   ├── freshness.js
│       │   ├── freshness.ts
│       │   ├── index-signatures.js
│       │   ├── index-signatures.ts
│       │   └── tsconfig.json
│       ├── functions.js
│       ├── functions.ts
│       ├── generics.js
│       ├── generics.ts
│       ├── interfaces.js
│       ├── interfaces.ts
│       ├── keyof.ts
│       ├── lib/
│       │   ├── exclude/
│       │   │   ├── nolibd.js
│       │   │   ├── nolibd.ts
│       │   │   └── tsconfig.json
│       │   └── usage/
│       │       ├── libd.js
│       │       ├── libd.ts
│       │       └── tsconfig.json
│       ├── libd.js
│       ├── literal-types.js
│       ├── literal-types.ts
│       ├── migrating/
│       │   ├── migrating.js
│       │   ├── migrating.ts
│       │   └── tsconfig.json
│       ├── readonly.js
│       ├── readonly.ts
│       ├── stringLiteralType.js
│       ├── tsconfig.json
│       ├── type-compatibility.js
│       ├── type-compatibility.ts
│       ├── type-inference.js
│       ├── type-inference.ts
│       ├── typeGuard.js
│       ├── typeGuard.ts
│       ├── types.js
│       └── types.ts
├── docs/
│   ├── arrow-functions.md
│   ├── async-await.md
│   ├── classes-emit.md
│   ├── classes.md
│   ├── compiler/
│   │   ├── ast-tip-children.md
│   │   ├── ast-tip-syntaxkind.md
│   │   ├── ast-trivia.md
│   │   ├── ast.md
│   │   ├── binder-container.md
│   │   ├── binder-declarations.md
│   │   ├── binder-diagnostics.md
│   │   ├── binder-functions.md
│   │   ├── binder-symbolflags.md
│   │   ├── binder-symboltable.md
│   │   ├── binder.md
│   │   ├── checker-diagnostics.md
│   │   ├── checker-global.md
│   │   ├── checker.md
│   │   ├── contributing.md
│   │   ├── emitter-functions.md
│   │   ├── emitter-sourcemaps.md
│   │   ├── emitter.md
│   │   ├── make-global.md
│   │   ├── overview.md
│   │   ├── parser-functions.md
│   │   ├── parser.md
│   │   ├── program.md
│   │   └── scanner.md
│   ├── compiler-options.md
│   ├── const.md
│   ├── declaration.md
│   ├── destructuring.md
│   ├── enums.md
│   ├── errors/
│   │   ├── common-errors.md
│   │   ├── interpreting-errors.md
│   │   └── main.md
│   ├── for...of.md
│   ├── future-javascript.md
│   ├── generators.md
│   ├── getting-started.md
│   ├── iterators.md
│   ├── javascript/
│   │   ├── closure.md
│   │   ├── equality.md
│   │   ├── null-undefined.md
│   │   ├── number.md
│   │   ├── recap.md
│   │   ├── references.md
│   │   ├── this.md
│   │   └── truthy.md
│   ├── jsx/
│   │   ├── others.md
│   │   ├── react.md
│   │   └── tsx.md
│   ├── let.md
│   ├── npm/
│   │   └── index.md
│   ├── options/
│   │   ├── intro.md
│   │   ├── noImplicitAny.md
│   │   └── strictNullChecks.md
│   ├── project/
│   │   ├── compilation-context.md
│   │   ├── declarationspaces.md
│   │   ├── dynamic-import-expressions.md
│   │   ├── external-modules.md
│   │   ├── files.md
│   │   ├── globals.md
│   │   ├── module-resolution.md
│   │   ├── modules.md
│   │   ├── namespaces.md
│   │   ├── project.md
│   │   └── tsconfig.md
│   ├── promise.md
│   ├── quick/
│   │   ├── browser.md
│   │   ├── library.md
│   │   └── nodejs.md
│   ├── rest-parameters.md
│   ├── spread-operator.md
│   ├── staging/
│   │   ├── async-await.md
│   │   └── generators.md
│   ├── state/
│   │   └── mobx.md
│   ├── styleguide/
│   │   ├── sample.js
│   │   ├── sample.ts
│   │   ├── styleguide.md
│   │   └── tsconfig.json
│   ├── template-strings.md
│   ├── testing/
│   │   ├── cypress.md
│   │   ├── intro.md
│   │   └── jest.md
│   ├── tips/
│   │   ├── barrel.md
│   │   ├── build-toggles.md
│   │   ├── classesAreUseful.md
│   │   ├── create-arrays.md
│   │   ├── currying.md
│   │   ├── defaultIsBad.md
│   │   ├── functionParameters.md
│   │   ├── jquery.md
│   │   ├── lazyObjectLiteralInitialization.md
│   │   ├── main.md
│   │   ├── nominalTyping.md
│   │   ├── outFile.md
│   │   ├── propertySetters.md
│   │   ├── singleton.md
│   │   ├── statefulFunctions.md
│   │   ├── staticConstructor.md
│   │   ├── stringEnums.md
│   │   ├── typeInstantiation.md
│   │   └── typed-event.md
│   ├── tools/
│   │   ├── changelog.md
│   │   ├── eslint.md
│   │   ├── husky.md
│   │   ├── intro.md
│   │   └── prettier.md
│   ├── types/
│   │   ├── @types.md
│   │   ├── advanced.md
│   │   ├── ambient/
│   │   │   ├── d.ts.md
│   │   │   ├── intro.md
│   │   │   └── variables.md
│   │   ├── callable.md
│   │   ├── discriminated-unions.md
│   │   ├── exceptions.md
│   │   ├── freshness.md
│   │   ├── functions.md
│   │   ├── generics.md
│   │   ├── index-signatures.md
│   │   ├── interfaces.md
│   │   ├── lib.d.ts.md
│   │   ├── literal-types.md
│   │   ├── migrating.md
│   │   ├── mixins.md
│   │   ├── moving-types.md
│   │   ├── never.md
│   │   ├── readonly.md
│   │   ├── type-assertion.md
│   │   ├── type-compatibility.md
│   │   ├── type-inference.md
│   │   ├── type-system.md
│   │   └── typeGuard.md
│   └── why-typescript.md
├── footer.md
├── header.html
├── images/
│   ├── promise states and fates.vsd
│   └── venn.vsd
└── snippets/
    └── md-snippets.cson

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitattributes
================================================
# core.autocrlf
* text=auto

*.js linguist-language=TypeScript


================================================
FILE: .github/workflows/build.yml
================================================
name: build ebook

on:
  push:
    branches:
      - master
  pull_request:
    branches:
      - master

jobs:
  build:
    runs-on: ubuntu-latest
    env:
      SHA: ${{ github.sha }}
    steps:
      - uses: actions/checkout@v1
      - uses: actions/setup-node@v1
        with:
          node-version: '12.18.2'
      - run: sudo apt update
      - run: sudo apt install libegl1 libopengl0 libxcb-cursor-dev
      - run: sudo -v && wget -nv -O- https://download.calibre-ebook.com/linux-installer.sh | sudo sh /dev/stdin
      - run: sudo npm install -g gitbook-cli
      - run: gitbook install
      - run: mkdir output
      - run: gitbook pdf . ./output/typescript-book-${SHA}.pdf
      - run: gitbook epub . ./output/typescript-book-${SHA}.epub
      - run: gitbook mobi . ./output/typescript-book-${SHA}.mobi
      - name: upload pdf artifact
        uses: actions/upload-artifact@v1
        with:
          name: typescript-book.pdf
          path: output/typescript-book-${{ env.SHA }}.pdf
      - name: upload epub artifact
        uses: actions/upload-artifact@v1
        with:
          name: typescript-book.epub
          path: output/typescript-book-${{ env.SHA }}.epub
      - name: upload mobi artifact
        uses: actions/upload-artifact@v1
        with:
          name: typescript-book.mobi
          path: output/typescript-book-${{ env.SHA }}.mobi


================================================
FILE: .gitignore
================================================
# Mac 
*.DS_Store

# IDEs
.alm
.vscode


# Node rules:
## Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

## Dependency directory
## Commenting this out is preferred by some people, see
## https://docs.npmjs.com/misc/faq#should-i-check-my-node_modules-folder-into-git
node_modules

# Book build output
_book

# eBook build output
*.epub
*.mobi
*.pdf


================================================
FILE: CONTRIBUTING.md
================================================
# Contributing

This book is developed using [GitBook](https://github.com/GitbookIO/gitbook). Authored in Markdown files (I use [atom](http://atom.io)).

Here's how to setup a Dev Environment:

```
npm install gitbook-cli -g
gitbook install
gitbook serve .
```
> Note: serve needs port `35729` (for live reload) and `4000` for serving http://localhost:4000.

Also 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).

# Code
All the code for the book is in the `/code` folder. Tested with `atom-typescript`.

### More Gitbook Tips
* Links best work if they are relative (e.g. `./foo.md`) to the *current* file.
* For links in the same file (`#foo-bar` style links) best to click the heading on github to get what gitbook expects.

### TypeScript Compiler Docs
Thanks 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.


================================================
FILE: GLOSSARY.md
================================================
# Duck Typing
If 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.

# OE
Operating 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.

# Incremental Parsing
Re-Parsing as the user edits the code.

================================================
FILE: LICENSE.md
================================================
Creative Commons 

https://creativecommons.org/licenses/by/4.0/


================================================
FILE: README.md
================================================
[![YouTube Channel Subscribers](https://img.shields.io/youtube/channel/subscribers/UCGD_0i6L48hucTiiyhb5QzQ?style=social)](https://www.youtube.com/@basarat)

TypeScript Deep Dive
=======

Learn 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) 🌹

## Reviews

* Thanks for the wonderful book. Learned a lot from it. ([link](https://www.gitbook.com/book/basarat/typescript/discussions/21#comment-1468279131934))
* Its probably the Best TypeScript book out there. Good Job ([link](https://twitter.com/thelondonjs/status/756419561570852864))
* Love how precise and clear the examples and explanations are! ([link](https://twitter.com/joe_mighty/status/758290957280346112))
* 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))
* Just a big thank you! **Best TypeScript 2 detailed explanation!** ([link](https://www.gitbook.com/book/basarat/typescript/discussions/38))
* This gitbook got my project going pronto. Fluent easy read 5 stars. ([link](https://twitter.com/thebabellion/status/779888195559235584))
* I recommend the online #typescript book by @basarat you'll love it.([link](https://twitter.com/markpieszak/status/788099306590969860))
* I've always found this by @basarat really helpful. ([link](https://twitter.com/Brocco/status/789887640656945152))
* We must highlight TypeScript Deep Dive, an open source book.([link](https://www.siliconrepublic.com/enterprise/typescript-programming-javascript))
* Great online resource for learning. ([link](https://twitter.com/rdfuhr/status/790193307708076035))
* 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))
* TypeScript Deep Dive is one of the best technical texts I've read in a while. ([link](https://twitter.com/borekb/status/794287092272599040))
* Thanks @basarat for the TypeScript Deep Dive Book. Help me a lot with my first TypeScript project. ([link](https://twitter.com/betolinck/status/797901548562960384))
* Thanks to @basarat for this great #typescript learning resource. ([link](https://twitter.com/markuse1501/status/799116176815230976))
* Guyz excellent book on Typescript(@typescriptlang) by @basarat ([link](https://twitter.com/deeinlove/status/813245965507260417))
* Leaning on the legendary @basarat's "TypeScript Deep Dive" book heavily at the moment ([link](https://twitter.com/sitapati/status/814379404956532737))
* numTimesPointedPeopleToBasaratsTypeScriptBook++; ([link](https://twitter.com/brocco/status/814227741696462848))
* 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)
* 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)
* Thank you for writing TypeScript Deep Dive. I have learned so much. [link](https://twitter.com/buctwbzs/status/857198618704355328?refsrc=email&s=11)
* Loving @basarat's @typescriptlang online book basarat.gitbooks.io/typescript/# loaded with great recipes! [link](https://twitter.com/ericliprandi/status/857608837309677568)
* 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)
* Thanks, this is a great book 🤓🤓 [link](https://twitter.com/jjwonmin/status/885666375548547073)
* Deep dive to typescript is awesome in so many levels. i find it very insightful. Thanks [link](https://twitter.com/orenmizr/status/891083492787970053)
* @basarat's intro to @typescriptlang is still one of the best going (if not THE best) [link](https://twitter.com/stevealee/status/953953255968698368)
* 
* This is sweet! So many #typescript goodies! [link](https://twitter.com/pauliescanlon/status/989898852474998784)

## Get Started
If you are here to read the book online [get started](https://basarat.gitbook.io/typescript/getting-started).

## Translations 
Book 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).
* [Filipino](https://github.com/themarshann/typescript-book-fil)
* [Italian](https://github.com/TizioFittizio/typescript-book)
* [Chinese](https://github.com/jkchao/typescript-book-chinese)
* [Russian](https://github.com/etroynov/typescript-book)
* [Portuguese](https://github.com/overlineink/typescript-book)
* [Japanese](https://github.com/yohamta/typescript-book)
* [Spanish](https://github.com/melissarofman/typescript-book)
* [Korean](https://github.com/radlohead/typescript-book)
* [French](https://github.com/HachemiH/typescript-book)
* [Polish](https://github.com/mbiesiad/typescript-book/tree/pl_PL)
* [Thai](https://github.com/futurouz/typescript-book)
* [Bengali](https://github.com/Acesif/typescript-book)
* [Ukrainian](https://github.com/ArtfulBits/typescript-book)

## Other Options
You 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.

## Special Thanks
All the amazing [contributors](https://github.com/basarat/typescript-book/graphs/contributors) 🌹

## Share
Share URL: https://basarat.gitbook.io/typescript/


================================================
FILE: SUMMARY.md
================================================
# Summary

* [Getting Started](docs/getting-started.md)
  * [Why TypeScript](docs/why-typescript.md)
* [JavaScript](docs/javascript/recap.md)
  * [Equality](docs/javascript/equality.md)
  * [References](docs/javascript/references.md)
  * [Null vs. Undefined](docs/javascript/null-undefined.md)
  * [this](docs/javascript/this.md)
  * [Closure](docs/javascript/closure.md)
  * [Number](docs/javascript/number.md)
  * [Truthy](docs/javascript/truthy.md)
* [Future JavaScript Now](docs/future-javascript.md)
  * [Classes](docs/classes.md)
    * [Classes Emit](docs/classes-emit.md)
  * [Arrow Functions](docs/arrow-functions.md)
  * [Rest Parameters](docs/rest-parameters.md)
  * [let](docs/let.md)
  * [const](docs/const.md)
  * [Destructuring](docs/destructuring.md)
  * [Spread Operator](docs/spread-operator.md)
  * [for...of](docs/for...of.md)
  * [Iterators](docs/iterators.md)
  * [Template Strings](docs/template-strings.md)
  * [Promise](docs/promise.md)
  * [Generators](docs/generators.md)
  * [Async Await](docs/async-await.md)
* [Project](docs/project/project.md)
  * [Compilation Context](docs/project/compilation-context.md)
    * [tsconfig.json](docs/project/tsconfig.md)
    * [Which Files?](docs/project/files.md)
  * [Declaration Spaces](docs/project/declarationspaces.md)
  * [Modules](docs/project/modules.md)
    * [File Module Details](docs/project/external-modules.md)
    * [global.d.ts](docs/project/globals.md)
  * [Namespaces](docs/project/namespaces.md)
  * [Dynamic Import Expressions](docs/project/dynamic-import-expressions.md)
* [Node.js QuickStart](docs/quick/nodejs.md)
* [Browser QuickStart](docs/quick/browser.md)
* [Library QuickStart](docs/quick/library.md)
* [TypeScript's Type System](docs/types/type-system.md)
  * [JS Migration Guide](docs/types/migrating.md)
  * [@types](docs/types/@types.md)
  * [Ambient Declarations](docs/types/ambient/intro.md)
    * [Declaration Files](docs/types/ambient/d.ts.md)
    * [Variables](docs/types/ambient/variables.md)
  * [Interfaces](docs/types/interfaces.md)
  * [Enums](docs/enums.md)
  * [`lib.d.ts`](docs/types/lib.d.ts.md)
  * [Functions](docs/types/functions.md)
  * [Callable](docs/types/callable.md)
  * [Type Assertion](docs/types/type-assertion.md)
  * [Freshness](docs/types/freshness.md)
  * [Type Guard](docs/types/typeGuard.md)
  * [Literal Types](docs/types/literal-types.md)
  * [Readonly](docs/types/readonly.md)
  * [Generics](docs/types/generics.md)
  * [Type Inference](docs/types/type-inference.md)
  * [Type Compatibility](docs/types/type-compatibility.md)
  * [Never Type](docs/types/never.md)
  * [Discriminated Unions](docs/types/discriminated-unions.md)
  * [Index Signatures](docs/types/index-signatures.md)
  * [Moving Types](docs/types/moving-types.md)
  * [Exception Handling](docs/types/exceptions.md)
  * [Mixins](docs/types/mixins.md)
* [JSX](docs/jsx/tsx.md)
  * [React](docs/jsx/react.md)
  * [Non React JSX](docs/jsx/others.md)
* [Options](docs/options/intro.md)
  * [noImplicitAny](docs/options/noImplicitAny.md)
  * [strictNullChecks](docs/options/strictNullChecks.md)
* [Errors in TypeScript](docs/errors/main.md)
  * [Interpreting Errors](docs/errors/interpreting-errors.md)
  * [Common Errors](docs/errors/common-errors.md)
* [NPM](docs/npm/index.md)
* [Testing](docs/testing/intro.md)
  * [Jest](docs/testing/jest.md)
  * [Cypress](docs/testing/cypress.md)
* [Tools](docs/tools/intro.md)
  * [Prettier](docs/tools/prettier.md)
  * [Husky](docs/tools/husky.md)
  * [ESLint](docs/tools/eslint.md)
  * [Changelog](docs/tools/changelog.md)
* [TIPs](docs/tips/main.md)
  * [String Based Enums](docs/tips/stringEnums.md)
  * [Nominal Typing](docs/tips/nominalTyping.md)
  * [Stateful Functions](docs/tips/statefulFunctions.md)
  * [Currying](docs/tips/currying.md)
  * [Type Instantiation](docs/tips/typeInstantiation.md)
  * [Lazy Object Literal Initialization](docs/tips/lazyObjectLiteralInitialization.md)
  * [Classes are Useful](docs/tips/classesAreUseful.md)
  * [Avoid Export Default](docs/tips/defaultIsBad.md)
  * [Limit Property Setters](docs/tips/propertySetters.md)
  * [`outFile` caution](docs/tips/outFile.md)
  * [JQuery tips](docs/tips/jquery.md)
  * [static constructors](docs/tips/staticConstructor.md)
  * [singleton pattern](docs/tips/singleton.md)
  * [Function parameters](docs/tips/functionParameters.md)
  * [Build Toggles](docs/tips/build-toggles.md)
  * [Barrel](docs/tips/barrel.md)
  * [Create Arrays](docs/tips/create-arrays.md)
  * [Typesafe Event Emitter](docs/tips/typed-event.md)
* [StyleGuide](docs/styleguide/styleguide.md)
* [TypeScript Compiler Internals](docs/compiler/overview.md)
  * [Program](docs/compiler/program.md)
  * [AST](docs/compiler/ast.md)
    * [TIP: Visit Children](docs/compiler/ast-tip-children.md)
    * [TIP: SyntaxKind enum](docs/compiler/ast-tip-syntaxkind.md)
    * [Trivia](docs/compiler/ast-trivia.md)
  * [Scanner](docs/compiler/scanner.md)
  * [Parser](docs/compiler/parser.md)
    * [Parser Functions](docs/compiler/parser-functions.md)
  * [Binder](docs/compiler/binder.md)
    * [Binder Functions](docs/compiler/binder-functions.md)
    * [Binder Declarations](docs/compiler/binder-declarations.md)
    * [Binder Container](docs/compiler/binder-container.md)
    * [Binder SymbolTable](docs/compiler/binder-symboltable.md)
    * [Binder Error Reporting](docs/compiler/binder-diagnostics.md)
  * [Checker](docs/compiler/checker.md)
    * [Checker Diagnostics](docs/compiler/checker-global.md)
    * [Checker Error Reporting](docs/compiler/checker-diagnostics.md)
  * [Emitter](docs/compiler/emitter.md)
    * [Emitter Functions](docs/compiler/emitter-functions.md)
    * [Emitter SourceMaps](docs/compiler/emitter-sourcemaps.md)
  * [Contributing](docs/compiler/contributing.md)


================================================
FILE: book.json
================================================
{
  "language": "en",
  "author": "Basarat Ali Syed",
  "title": "TypeScript Deep Dive",
  "plugins": ["edit-link", "github", "adsense","header"],
  "pluginsConfig": {
    "layout": {
      "headerPath" : "header.html"
    },
    "lunr": {
      "ignoreSpecialCharacters": true
    },
    "edit-link": {
      "base": "https://github.com/basarat/typescript-book/tree/master",
      "label": "Edit This Page"
    },
    "github": {
      "url": "https://github.com/basarat/typescript-book/"
    },
    "adsense": {
      "client": "ca-pub-4656761253552116",
      "slot": "2017468453",
      "format": "auto",
      "element": ".page-inner section",
      "position": "bottom"
    }
  }
}


================================================
FILE: code/async-await/es5/asyncAwaitES5.js
================================================
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [0, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
function delay(milliseconds, count) {
    return new Promise(function (resolve) {
        setTimeout(function () {
            resolve(count);
        }, milliseconds);
    });
}
// async function always return a Promise
function dramaticWelcome() {
    return __awaiter(this, void 0, void 0, function () {
        var i, count;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    console.log("Hello");
                    i = 0;
                    _a.label = 1;
                case 1:
                    if (!(i < 5)) return [3 /*break*/, 4];
                    return [4 /*yield*/, delay(500, i)];
                case 2:
                    count = _a.sent();
                    console.log(count);
                    _a.label = 3;
                case 3:
                    i++;
                    return [3 /*break*/, 1];
                case 4:
                    console.log("World!");
                    return [2 /*return*/];
            }
        });
    });
}
dramaticWelcome();


================================================
FILE: code/async-await/es5/asyncAwaitES5.ts
================================================
function delay(milliseconds: number, count: number): Promise<number> {
    return new Promise<number>(resolve => {
            setTimeout(() => {
                resolve(count);
            }, milliseconds);
        });
}

// async function always return a Promise
async function dramaticWelcome(): Promise<void> {
    console.log("Hello");

    for (let i = 0; i < 5; i++) {
        // await is converting Promise<number> into number
        const count: number = await delay(500, i);
        console.log(count);
    }

    console.log("World!");
}

dramaticWelcome();

================================================
FILE: code/async-await/es5/tsconfig.json
================================================
{
  "compilerOptions": {
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'. */
    "lib": ["dom", "es2015.promise", "es5"]  /* Specify library files to be included in the compilation:  */
  },
    "files": [
      "./asyncAwaitES5.ts"
  ]
}

================================================
FILE: code/async-await/es6/asyncAwaitES6.js
================================================
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
function delay(milliseconds, count) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(count);
        }, milliseconds);
    });
}
// async function always return a Promise
function dramaticWelcome() {
    return __awaiter(this, void 0, void 0, function* () {
        console.log("Hello");
        for (let i = 0; i < 5; i++) {
            // await is converting Promise<number> into number
            const count = yield delay(500, i);
            console.log(count);
        }
        console.log("World!");
    });
}
dramaticWelcome();


================================================
FILE: code/async-await/es6/asyncAwaitES6.ts
================================================
function delay(milliseconds: number, count: number): Promise<number> {
    return new Promise<number>(resolve => {
            setTimeout(() => {
                resolve(count);
            }, milliseconds);
        });
}

// async function always return a Promise
async function dramaticWelcome(): Promise<void> {
    console.log("Hello");

    for (let i = 0; i < 5; i++) {
        // await is converting Promise<number> into number
        const count: number = await delay(500, i);
        console.log(count);
    }

    console.log("World!");
}

dramaticWelcome();

================================================
FILE: code/async-await/es6/tsconfig.json
================================================
{
  "compilerOptions": {
    "target": "es6",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
    "module": "commonjs"                     /* Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'. */
  },
    "files": [
      "./asyncAwaitES6.ts"
  ]
}

================================================
FILE: code/compiler/package.json
================================================
{
  "name": "compiler",
  "version": "1.0.0",
  "description": "",
  "main": "runScanner.js",
  "dependencies": {
    "ntypescript": "1.201507141013.1"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


================================================
FILE: code/compiler/parser/runParser.js
================================================
var ts = require("ntypescript");
function printAllChildren(node, depth) {
    if (depth === void 0) { depth = 0; }
    console.log(new Array(depth + 1).join('----'), ts.syntaxKindToName(node.kind), node.pos, node.end);
    depth++;
    node.getChildren().forEach(function (c) { return printAllChildren(c, depth); });
}
var sourceCode = "\nvar foo = 123;\n".trim();
var sourceFile = ts.createSourceFile('foo.ts', sourceCode, 1, true);
printAllChildren(sourceFile);


================================================
FILE: code/compiler/parser/runParser.ts
================================================
import * as ts from "ntypescript";

function printAllChildren(node: ts.Node, depth = 0) {
    console.log(new Array(depth + 1).join('----'), ts.syntaxKindToName(node.kind), node.pos, node.end);
    depth++;
    node.getChildren().forEach(c=> printAllChildren(c, depth));
}

var sourceCode = `
var foo = 123;
`.trim();

var sourceFile = ts.createSourceFile('foo.ts', sourceCode, ts.ScriptTarget.ES5, true);
printAllChildren(sourceFile);

================================================
FILE: code/compiler/scanner/runScanner.js
================================================
var ts = require("ntypescript");
var scanner = ts.createScanner(2, true);
function initializeState(text) {
    scanner.setText(text);
    scanner.setOnError(function (message, length) {
        console.error(message);
    });
    scanner.setScriptTarget(1);
    scanner.setLanguageVariant(0);
}
initializeState("\nvar foo = 123;\n".trim());
var token = scanner.scan();
while (token != 1) {
    console.log(ts.syntaxKindToName(token));
    token = scanner.scan();
}


================================================
FILE: code/compiler/scanner/runScanner.ts
================================================
import * as ts from "ntypescript";

// TypeScript has a singelton scanner
const scanner = ts.createScanner(ts.ScriptTarget.Latest, /*skipTrivia*/ true);

// That is initialized using a function `initializeState` similar to
function initializeState(text: string) {
    scanner.setText(text);
    scanner.setOnError((message: ts.DiagnosticMessage, length: number) => {
        console.error(message);
    });
    scanner.setScriptTarget(ts.ScriptTarget.ES5);
    scanner.setLanguageVariant(ts.LanguageVariant.Standard);
}

// Sample usage
initializeState(`
var foo = 123;
`.trim());

// Start the scanning
var token = scanner.scan();
while (token != ts.SyntaxKind.EndOfFileToken) {
    console.log(ts.syntaxKindToName(token));
    token = scanner.scan();
}


================================================
FILE: code/compiler/scanner/runScannerWithPositions.js
================================================
var ts = require("ntypescript");
var scanner = ts.createScanner(2, true);
function initializeState(text) {
    scanner.setText(text);
    scanner.setOnError(function (message, length) {
        console.error(message);
    });
    scanner.setScriptTarget(1);
    scanner.setLanguageVariant(0);
}
initializeState("\nvar foo = 123;\n".trim());
var token = scanner.scan();
while (token != 1) {
    var currentToken = ts.syntaxKindToName(token);
    var tokenStart = scanner.getStartPos();
    token = scanner.scan();
    var tokenEnd = scanner.getStartPos();
    console.log(currentToken, tokenStart, tokenEnd);
}


================================================
FILE: code/compiler/scanner/runScannerWithPositions.ts
================================================
import * as ts from "ntypescript";

// TypeScript has a singelton scanner
const scanner = ts.createScanner(ts.ScriptTarget.Latest, /*skipTrivia*/ true);

// That is initialized using a function `initializeState` similar to
function initializeState(text: string) {
    scanner.setText(text);
    scanner.setOnError((message: ts.DiagnosticMessage, length: number) => {
        console.error(message);
    });
    scanner.setScriptTarget(ts.ScriptTarget.ES5);
    scanner.setLanguageVariant(ts.LanguageVariant.Standard);
}

// Sample usage
initializeState(`
var foo = 123;
`.trim());

// Start the scanning
var token = scanner.scan();
while (token != ts.SyntaxKind.EndOfFileToken) {
    let currentToken = ts.syntaxKindToName(token);
    let tokenStart = scanner.getStartPos();
    token = scanner.scan();
    let tokenEnd = scanner.getStartPos();
    console.log(currentToken, tokenStart, tokenEnd);
}


================================================
FILE: code/compiler/tsconfig.json
================================================
{
    "version": "1.5.0-beta",
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "isolatedModules": false,
        "jsx": "react",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "declaration": false,
        "noImplicitAny": false,
        "removeComments": true,
        "noLib": false,
        "preserveConstEnums": true,
        "suppressImplicitAnyIndexErrors": true
    },
    "filesGlob": [
        "./**/*.ts",
        "./**/*.tsx",
        "!./node_modules/**/*"
    ],
    "files": [
        "./parser/runParser.ts",
        "./scanner/runScanner.ts",
        "./scanner/runScannerWithPositions.ts",
        "./typings/node/node.d.ts",
        "./typings/tsd.d.ts"
    ]
}


================================================
FILE: code/compiler/tsd.json
================================================
{
  "version": "v4",
  "repo": "borisyankov/DefinitelyTyped",
  "ref": "master",
  "path": "typings",
  "bundle": "typings/tsd.d.ts",
  "installed": {
    "node/node.d.ts": {
      "commit": "38c6ccfde0e67ff10d7408e0ee8b7720b3f21d3b"
    }
  }
}


================================================
FILE: code/compiler/typings/node/node.d.ts
================================================
// Type definitions for Node.js v0.12.0
// Project: http://nodejs.org/
// Definitions by: Microsoft TypeScript <http://typescriptlang.org>, DefinitelyTyped <https://github.com/borisyankov/DefinitelyTyped>
// Definitions: https://github.com/borisyankov/DefinitelyTyped

/************************************************
*                                               *
*               Node.js v0.12.0 API             *
*                                               *
************************************************/

/************************************************
*                                               *
*                   GLOBAL                      *
*                                               *
************************************************/
declare var process: NodeJS.Process;
declare var global: NodeJS.Global;

declare var __filename: string;
declare var __dirname: string;

declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer;
declare function clearTimeout(timeoutId: NodeJS.Timer): void;
declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer;
declare function clearInterval(intervalId: NodeJS.Timer): void;
declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any;
declare function clearImmediate(immediateId: any): void;

declare var require: {
    (id: string): any;
    resolve(id:string): string;
    cache: any;
    extensions: any;
    main: any;
};

declare var module: {
    exports: any;
    require(id: string): any;
    id: string;
    filename: string;
    loaded: boolean;
    parent: any;
    children: any[];
};

// Same as module.exports
declare var exports: any;
declare var SlowBuffer: {
    new (str: string, encoding?: string): Buffer;
    new (size: number): Buffer;
    new (size: Uint8Array): Buffer;
    new (array: any[]): Buffer;
    prototype: Buffer;
    isBuffer(obj: any): boolean;
    byteLength(string: string, encoding?: string): number;
    concat(list: Buffer[], totalLength?: number): Buffer;
};


// Buffer class
interface Buffer extends NodeBuffer {}

/**
 * Raw data is stored in instances of the Buffer class.
 * 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.
 * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex'
 */
declare var Buffer: {
    /**
     * Allocates a new buffer containing the given {str}.
     *
     * @param str String to store in buffer.
     * @param encoding encoding to use, optional.  Default is 'utf8'
     */
    new (str: string, encoding?: string): Buffer;
    /**
     * Allocates a new buffer of {size} octets.
     *
     * @param size count of octets to allocate.
     */
    new (size: number): Buffer;
    /**
     * Allocates a new buffer containing the given {array} of octets.
     *
     * @param array The octets to store.
     */
    new (array: Uint8Array): Buffer;
    /**
     * Allocates a new buffer containing the given {array} of octets.
     *
     * @param array The octets to store.
     */
    new (array: any[]): Buffer;
    prototype: Buffer;
    /**
     * Returns true if {obj} is a Buffer
     *
     * @param obj object to test.
     */
    isBuffer(obj: any): boolean;
    /**
     * Returns true if {encoding} is a valid encoding argument.
     * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex'
     *
     * @param encoding string to test.
     */
    isEncoding(encoding: string): boolean;
    /**
     * Gives the actual byte length of a string. encoding defaults to 'utf8'.
     * This is not the same as String.prototype.length since that returns the number of characters in a string.
     *
     * @param string string to test.
     * @param encoding encoding used to evaluate (defaults to 'utf8')
     */
    byteLength(string: string, encoding?: string): number;
    /**
     * Returns a buffer which is the result of concatenating all the buffers in the list together.
     *
     * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer.
     * If the list has exactly one item, then the first item of the list is returned.
     * If the list has more than one item, then a new Buffer is created.
     *
     * @param list An array of Buffer objects to concatenate
     * @param totalLength Total length of the buffers when concatenated.
     *   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.
     */
    concat(list: Buffer[], totalLength?: number): Buffer;
    /**
     * The same as buf1.compare(buf2).
     */
    compare(buf1: Buffer, buf2: Buffer): number;
};

/************************************************
*                                               *
*               GLOBAL INTERFACES               *
*                                               *
************************************************/
declare module NodeJS {
    export interface ErrnoException extends Error {
        errno?: number;
        code?: string;
        path?: string;
        syscall?: string;
        stack?: string;
    }

    export interface EventEmitter {
        addListener(event: string, listener: Function): EventEmitter;
        on(event: string, listener: Function): EventEmitter;
        once(event: string, listener: Function): EventEmitter;
        removeListener(event: string, listener: Function): EventEmitter;
        removeAllListeners(event?: string): EventEmitter;
        setMaxListeners(n: number): void;
        listeners(event: string): Function[];
        emit(event: string, ...args: any[]): boolean;
    }

    export interface ReadableStream extends EventEmitter {
        readable: boolean;
        read(size?: number): string|Buffer;
        setEncoding(encoding: string): void;
        pause(): void;
        resume(): void;
        pipe<T extends WritableStream>(destination: T, options?: { end?: boolean; }): T;
        unpipe<T extends WritableStream>(destination?: T): void;
        unshift(chunk: string): void;
        unshift(chunk: Buffer): void;
        wrap(oldStream: ReadableStream): ReadableStream;
    }

    export interface WritableStream extends EventEmitter {
        writable: boolean;
        write(buffer: Buffer, cb?: Function): boolean;
        write(str: string, cb?: Function): boolean;
        write(str: string, encoding?: string, cb?: Function): boolean;
        end(): void;
        end(buffer: Buffer, cb?: Function): void;
        end(str: string, cb?: Function): void;
        end(str: string, encoding?: string, cb?: Function): void;
    }

    export interface ReadWriteStream extends ReadableStream, WritableStream {}

    export interface Process extends EventEmitter {
        stdout: WritableStream;
        stderr: WritableStream;
        stdin: ReadableStream;
        argv: string[];
        execPath: string;
        abort(): void;
        chdir(directory: string): void;
        cwd(): string;
        env: any;
        exit(code?: number): void;
        getgid(): number;
        setgid(id: number): void;
        setgid(id: string): void;
        getuid(): number;
        setuid(id: number): void;
        setuid(id: string): void;
        version: string;
        versions: {
            http_parser: string;
            node: string;
            v8: string;
            ares: string;
            uv: string;
            zlib: string;
            openssl: string;
        };
        config: {
            target_defaults: {
                cflags: any[];
                default_configuration: string;
                defines: string[];
                include_dirs: string[];
                libraries: string[];
            };
            variables: {
                clang: number;
                host_arch: string;
                node_install_npm: boolean;
                node_install_waf: boolean;
                node_prefix: string;
                node_shared_openssl: boolean;
                node_shared_v8: boolean;
                node_shared_zlib: boolean;
                node_use_dtrace: boolean;
                node_use_etw: boolean;
                node_use_openssl: boolean;
                target_arch: string;
                v8_no_strict_aliasing: number;
                v8_use_snapshot: boolean;
                visibility: string;
            };
        };
        kill(pid: number, signal?: string): void;
        pid: number;
        title: string;
        arch: string;
        platform: string;
        memoryUsage(): { rss: number; heapTotal: number; heapUsed: number; };
        nextTick(callback: Function): void;
        umask(mask?: number): number;
        uptime(): number;
        hrtime(time?:number[]): number[];

        // Worker
        send?(message: any, sendHandle?: any): void;
    }

    export interface Global {
        Array: typeof Array;
        ArrayBuffer: typeof ArrayBuffer;
        Boolean: typeof Boolean;
        Buffer: typeof Buffer;
        DataView: typeof DataView;
        Date: typeof Date;
        Error: typeof Error;
        EvalError: typeof EvalError;
        Float32Array: typeof Float32Array;
        Float64Array: typeof Float64Array;
        Function: typeof Function;
        GLOBAL: Global;
        Infinity: typeof Infinity;
        Int16Array: typeof Int16Array;
        Int32Array: typeof Int32Array;
        Int8Array: typeof Int8Array;
        Intl: typeof Intl;
        JSON: typeof JSON;
        Map: typeof Map;
        Math: typeof Math;
        NaN: typeof NaN;
        Number: typeof Number;
        Object: typeof Object;
        Promise: Function;
        RangeError: typeof RangeError;
        ReferenceError: typeof ReferenceError;
        RegExp: typeof RegExp;
        Set: typeof Set;
        String: typeof String;
        Symbol: Function;
        SyntaxError: typeof SyntaxError;
        TypeError: typeof TypeError;
        URIError: typeof URIError;
        Uint16Array: typeof Uint16Array;
        Uint32Array: typeof Uint32Array;
        Uint8Array: typeof Uint8Array;
        Uint8ClampedArray: Function;
        WeakMap: typeof WeakMap;
        WeakSet: Function;
        clearImmediate: (immediateId: any) => void;
        clearInterval: (intervalId: NodeJS.Timer) => void;
        clearTimeout: (timeoutId: NodeJS.Timer) => void;
        console: typeof console;
        decodeURI: typeof decodeURI;
        decodeURIComponent: typeof decodeURIComponent;
        encodeURI: typeof encodeURI;
        encodeURIComponent: typeof encodeURIComponent;
        escape: (str: string) => string;
        eval: typeof eval;
        global: Global;
        isFinite: typeof isFinite;
        isNaN: typeof isNaN;
        parseFloat: typeof parseFloat;
        parseInt: typeof parseInt;
        process: Process;
        root: Global;
        setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any;
        setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer;
        setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer;
        undefined: typeof undefined;
        unescape: (str: string) => string;
        gc: () => void;
    }

    export interface Timer {
        ref() : void;
        unref() : void;
    }
}

/**
 * @deprecated
 */
interface NodeBuffer {
    [index: number]: number;
    write(string: string, offset?: number, length?: number, encoding?: string): number;
    toString(encoding?: string, start?: number, end?: number): string;
    toJSON(): any;
    length: number;
    equals(otherBuffer: Buffer): boolean;
    compare(otherBuffer: Buffer): number;
    copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
    slice(start?: number, end?: number): Buffer;
    writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
    writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
    writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
    writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
    readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
    readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
    readIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
    readIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
    readUInt8(offset: number, noAsset?: boolean): number;
    readUInt16LE(offset: number, noAssert?: boolean): number;
    readUInt16BE(offset: number, noAssert?: boolean): number;
    readUInt32LE(offset: number, noAssert?: boolean): number;
    readUInt32BE(offset: number, noAssert?: boolean): number;
    readInt8(offset: number, noAssert?: boolean): number;
    readInt16LE(offset: number, noAssert?: boolean): number;
    readInt16BE(offset: number, noAssert?: boolean): number;
    readInt32LE(offset: number, noAssert?: boolean): number;
    readInt32BE(offset: number, noAssert?: boolean): number;
    readFloatLE(offset: number, noAssert?: boolean): number;
    readFloatBE(offset: number, noAssert?: boolean): number;
    readDoubleLE(offset: number, noAssert?: boolean): number;
    readDoubleBE(offset: number, noAssert?: boolean): number;
    writeUInt8(value: number, offset: number, noAssert?: boolean): void;
    writeUInt16LE(value: number, offset: number, noAssert?: boolean): void;
    writeUInt16BE(value: number, offset: number, noAssert?: boolean): void;
    writeUInt32LE(value: number, offset: number, noAssert?: boolean): void;
    writeUInt32BE(value: number, offset: number, noAssert?: boolean): void;
    writeInt8(value: number, offset: number, noAssert?: boolean): void;
    writeInt16LE(value: number, offset: number, noAssert?: boolean): void;
    writeInt16BE(value: number, offset: number, noAssert?: boolean): void;
    writeInt32LE(value: number, offset: number, noAssert?: boolean): void;
    writeInt32BE(value: number, offset: number, noAssert?: boolean): void;
    writeFloatLE(value: number, offset: number, noAssert?: boolean): void;
    writeFloatBE(value: number, offset: number, noAssert?: boolean): void;
    writeDoubleLE(value: number, offset: number, noAssert?: boolean): void;
    writeDoubleBE(value: number, offset: number, noAssert?: boolean): void;
    fill(value: any, offset?: number, end?: number): void;
}

/************************************************
*                                               *
*                   MODULES                     *
*                                               *
************************************************/
declare module "buffer" {
    export var INSPECT_MAX_BYTES: number;
}

declare module "querystring" {
    export function stringify(obj: any, sep?: string, eq?: string): string;
    export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any;
    export function escape(str: string): string;
    export function unescape(str: string): string;
}

declare module "events" {
    export class EventEmitter implements NodeJS.EventEmitter {
        static listenerCount(emitter: EventEmitter, event: string): number;

        addListener(event: string, listener: Function): EventEmitter;
        on(event: string, listener: Function): EventEmitter;
        once(event: string, listener: Function): EventEmitter;
        removeListener(event: string, listener: Function): EventEmitter;
        removeAllListeners(event?: string): EventEmitter;
        setMaxListeners(n: number): void;
        listeners(event: string): Function[];
        emit(event: string, ...args: any[]): boolean;
   }
}

declare module "http" {
    import events = require("events");
    import net = require("net");
    import stream = require("stream");

    export interface Server extends events.EventEmitter {
        listen(port: number, hostname?: string, backlog?: number, callback?: Function): Server;
        listen(port: number, hostname?: string, callback?: Function): Server;
        listen(path: string, callback?: Function): Server;
        listen(handle: any, listeningListener?: Function): Server;
        close(cb?: any): Server;
        address(): { port: number; family: string; address: string; };
        maxHeadersCount: number;
    }
    /**
     * @deprecated Use IncomingMessage
     */
    export interface ServerRequest extends IncomingMessage {
        connection: net.Socket;
    }
    export interface ServerResponse extends events.EventEmitter, stream.Writable {
        // Extended base methods
        write(buffer: Buffer): boolean;
        write(buffer: Buffer, cb?: Function): boolean;
        write(str: string, cb?: Function): boolean;
        write(str: string, encoding?: string, cb?: Function): boolean;
        write(str: string, encoding?: string, fd?: string): boolean;

        writeContinue(): void;
        writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void;
        writeHead(statusCode: number, headers?: any): void;
        statusCode: number;
        setHeader(name: string, value: string): void;
        sendDate: boolean;
        getHeader(name: string): string;
        removeHeader(name: string): void;
        write(chunk: any, encoding?: string): any;
        addTrailers(headers: any): void;

        // Extended base methods
        end(): void;
        end(buffer: Buffer, cb?: Function): void;
        end(str: string, cb?: Function): void;
        end(str: string, encoding?: string, cb?: Function): void;
        end(data?: any, encoding?: string): void;
    }
    export interface ClientRequest extends events.EventEmitter, stream.Writable {
        // Extended base methods
        write(buffer: Buffer): boolean;
        write(buffer: Buffer, cb?: Function): boolean;
        write(str: string, cb?: Function): boolean;
        write(str: string, encoding?: string, cb?: Function): boolean;
        write(str: string, encoding?: string, fd?: string): boolean;

        write(chunk: any, encoding?: string): void;
        abort(): void;
        setTimeout(timeout: number, callback?: Function): void;
        setNoDelay(noDelay?: boolean): void;
        setSocketKeepAlive(enable?: boolean, initialDelay?: number): void;

        // Extended base methods
        end(): void;
        end(buffer: Buffer, cb?: Function): void;
        end(str: string, cb?: Function): void;
        end(str: string, encoding?: string, cb?: Function): void;
        end(data?: any, encoding?: string): void;
    }
    export interface IncomingMessage extends events.EventEmitter, stream.Readable {
        httpVersion: string;
        headers: any;
        rawHeaders: string[];
        trailers: any;
        rawTrailers: any;
        setTimeout(msecs: number, callback: Function): NodeJS.Timer;
        /**
         * Only valid for request obtained from http.Server.
         */
        method?: string;
        /**
         * Only valid for request obtained from http.Server.
         */
        url?: string;
        /**
         * Only valid for response obtained from http.ClientRequest.
         */
        statusCode?: number;
        /**
         * Only valid for response obtained from http.ClientRequest.
         */
        statusMessage?: string;
        socket: net.Socket;
    }
    /**
     * @deprecated Use IncomingMessage
     */
    export interface ClientResponse extends IncomingMessage { }

	export interface AgentOptions {
		/**
		 * Keep sockets around in a pool to be used by other requests in the future. Default = false
		 */
		keepAlive?: boolean;
		/**
		 * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000.
		 * Only relevant if keepAlive is set to true.
		 */
		keepAliveMsecs?: number;
		/**
		 * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity
		 */
		maxSockets?: number;
		/**
		 * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256.
		 */
		maxFreeSockets?: number;
	}

    export class Agent {
		maxSockets: number;
		sockets: any;
		requests: any;

		constructor(opts?: AgentOptions);

		/**
		 * Destroy any sockets that are currently in use by the agent.
		 * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled,
		 * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise,
		 * sockets may hang open for quite a long time before the server terminates them.
		 */
		destroy(): void;
	}

    export var METHODS: string[];

    export var STATUS_CODES: {
        [errorCode: number]: string;
        [errorCode: string]: string;
    };
    export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) =>void ): Server;
    export function createClient(port?: number, host?: string): any;
    export function request(options: any, callback?: (res: IncomingMessage) => void): ClientRequest;
    export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest;
    export var globalAgent: Agent;
}

declare module "cluster" {
    import child  = require("child_process");
    import events = require("events");

    export interface ClusterSettings {
        exec?: string;
        args?: string[];
        silent?: boolean;
    }

    export class Worker extends events.EventEmitter {
        id: string;
        process: child.ChildProcess;
        suicide: boolean;
        send(message: any, sendHandle?: any): void;
        kill(signal?: string): void;
        destroy(signal?: string): void;
        disconnect(): void;
    }

    export var settings: ClusterSettings;
    export var isMaster: boolean;
    export var isWorker: boolean;
    export function setupMaster(settings?: ClusterSettings): void;
    export function fork(env?: any): Worker;
    export function disconnect(callback?: Function): void;
    export var worker: Worker;
    export var workers: Worker[];

    // Event emitter
    export function addListener(event: string, listener: Function): void;
    export function on(event: string, listener: Function): any;
    export function once(event: string, listener: Function): void;
    export function removeListener(event: string, listener: Function): void;
    export function removeAllListeners(event?: string): void;
    export function setMaxListeners(n: number): void;
    export function listeners(event: string): Function[];
    export function emit(event: string, ...args: any[]): boolean;
}

declare module "zlib" {
    import stream = require("stream");
    export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; }

    export interface Gzip extends stream.Transform { }
    export interface Gunzip extends stream.Transform { }
    export interface Deflate extends stream.Transform { }
    export interface Inflate extends stream.Transform { }
    export interface DeflateRaw extends stream.Transform { }
    export interface InflateRaw extends stream.Transform { }
    export interface Unzip extends stream.Transform { }

    export function createGzip(options?: ZlibOptions): Gzip;
    export function createGunzip(options?: ZlibOptions): Gunzip;
    export function createDeflate(options?: ZlibOptions): Deflate;
    export function createInflate(options?: ZlibOptions): Inflate;
    export function createDeflateRaw(options?: ZlibOptions): DeflateRaw;
    export function createInflateRaw(options?: ZlibOptions): InflateRaw;
    export function createUnzip(options?: ZlibOptions): Unzip;

    export function deflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void;
    export function deflateSync(buf: Buffer, options?: ZlibOptions): any;
    export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void;
    export function deflateRawSync(buf: Buffer, options?: ZlibOptions): any;
    export function gzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void;
    export function gzipSync(buf: Buffer, options?: ZlibOptions): any;
    export function gunzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void;
    export function gunzipSync(buf: Buffer, options?: ZlibOptions): any;
    export function inflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void;
    export function inflateSync(buf: Buffer, options?: ZlibOptions): any;
    export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void;
    export function inflateRawSync(buf: Buffer, options?: ZlibOptions): any;
    export function unzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void;
    export function unzipSync(buf: Buffer, options?: ZlibOptions): any;

    // Constants
    export var Z_NO_FLUSH: number;
    export var Z_PARTIAL_FLUSH: number;
    export var Z_SYNC_FLUSH: number;
    export var Z_FULL_FLUSH: number;
    export var Z_FINISH: number;
    export var Z_BLOCK: number;
    export var Z_TREES: number;
    export var Z_OK: number;
    export var Z_STREAM_END: number;
    export var Z_NEED_DICT: number;
    export var Z_ERRNO: number;
    export var Z_STREAM_ERROR: number;
    export var Z_DATA_ERROR: number;
    export var Z_MEM_ERROR: number;
    export var Z_BUF_ERROR: number;
    export var Z_VERSION_ERROR: number;
    export var Z_NO_COMPRESSION: number;
    export var Z_BEST_SPEED: number;
    export var Z_BEST_COMPRESSION: number;
    export var Z_DEFAULT_COMPRESSION: number;
    export var Z_FILTERED: number;
    export var Z_HUFFMAN_ONLY: number;
    export var Z_RLE: number;
    export var Z_FIXED: number;
    export var Z_DEFAULT_STRATEGY: number;
    export var Z_BINARY: number;
    export var Z_TEXT: number;
    export var Z_ASCII: number;
    export var Z_UNKNOWN: number;
    export var Z_DEFLATED: number;
    export var Z_NULL: number;
}

declare module "os" {
    export function tmpdir(): string;
    export function hostname(): string;
    export function type(): string;
    export function platform(): string;
    export function arch(): string;
    export function release(): string;
    export function uptime(): number;
    export function loadavg(): number[];
    export function totalmem(): number;
    export function freemem(): number;
    export function cpus(): { model: string; speed: number; times: { user: number; nice: number; sys: number; idle: number; irq: number; }; }[];
    export function networkInterfaces(): any;
    export var EOL: string;
}

declare module "https" {
    import tls = require("tls");
    import events = require("events");
    import http = require("http");

    export interface ServerOptions {
        pfx?: any;
        key?: any;
        passphrase?: string;
        cert?: any;
        ca?: any;
        crl?: any;
        ciphers?: string;
        honorCipherOrder?: boolean;
        requestCert?: boolean;
        rejectUnauthorized?: boolean;
        NPNProtocols?: any;
        SNICallback?: (servername: string) => any;
    }

    export interface RequestOptions {
        host?: string;
        hostname?: string;
        port?: number;
        path?: string;
        method?: string;
        headers?: any;
        auth?: string;
        agent?: any;
        pfx?: any;
        key?: any;
        passphrase?: string;
        cert?: any;
        ca?: any;
        ciphers?: string;
        rejectUnauthorized?: boolean;
    }

    export interface Agent {
        maxSockets: number;
        sockets: any;
        requests: any;
    }
    export var Agent: {
        new (options?: RequestOptions): Agent;
    };
    export interface Server extends tls.Server { }
    export function createServer(options: ServerOptions, requestListener?: Function): Server;
    export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest;
    export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest;
    export var globalAgent: Agent;
}

declare module "punycode" {
    export function decode(string: string): string;
    export function encode(string: string): string;
    export function toUnicode(domain: string): string;
    export function toASCII(domain: string): string;
    export var ucs2: ucs2;
    interface ucs2 {
        decode(string: string): string;
        encode(codePoints: number[]): string;
    }
    export var version: any;
}

declare module "repl" {
    import stream = require("stream");
    import events = require("events");

    export interface ReplOptions {
        prompt?: string;
        input?: NodeJS.ReadableStream;
        output?: NodeJS.WritableStream;
        terminal?: boolean;
        eval?: Function;
        useColors?: boolean;
        useGlobal?: boolean;
        ignoreUndefined?: boolean;
        writer?: Function;
    }
    export function start(options: ReplOptions): events.EventEmitter;
}

declare module "readline" {
    import events = require("events");
    import stream = require("stream");

    export interface ReadLine extends events.EventEmitter {
        setPrompt(prompt: string, length: number): void;
        prompt(preserveCursor?: boolean): void;
        question(query: string, callback: Function): void;
        pause(): void;
        resume(): void;
        close(): void;
        write(data: any, key?: any): void;
    }
    export interface ReadLineOptions {
        input: NodeJS.ReadableStream;
        output: NodeJS.WritableStream;
        completer?: Function;
        terminal?: boolean;
    }
    export function createInterface(options: ReadLineOptions): ReadLine;
}

declare module "vm" {
    export interface Context { }
    export interface Script {
        runInThisContext(): void;
        runInNewContext(sandbox?: Context): void;
    }
    export function runInThisContext(code: string, filename?: string): void;
    export function runInNewContext(code: string, sandbox?: Context, filename?: string): void;
    export function runInContext(code: string, context: Context, filename?: string): void;
    export function createContext(initSandbox?: Context): Context;
    export function createScript(code: string, filename?: string): Script;
}

declare module "child_process" {
    import events = require("events");
    import stream = require("stream");

    export interface ChildProcess extends events.EventEmitter {
        stdin:  stream.Writable;
        stdout: stream.Readable;
        stderr: stream.Readable;
        pid: number;
        kill(signal?: string): void;
        send(message: any, sendHandle?: any): void;
        disconnect(): void;
    }

    export function spawn(command: string, args?: string[], options?: {
        cwd?: string;
        stdio?: any;
        custom?: any;
        env?: any;
        detached?: boolean;
    }): ChildProcess;
    export function exec(command: string, options: {
        cwd?: string;
        stdio?: any;
        customFds?: any;
        env?: any;
        encoding?: string;
        timeout?: number;
        maxBuffer?: number;
        killSignal?: string;
    }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
    export function exec(command: string, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
    export function execFile(file: string,
        callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
    export function execFile(file: string, args?: string[],
        callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
    export function execFile(file: string, args?: string[], options?: {
        cwd?: string;
        stdio?: any;
        customFds?: any;
        env?: any;
        encoding?: string;
        timeout?: number;
        maxBuffer?: string;
        killSignal?: string;
    }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
    export function fork(modulePath: string, args?: string[], options?: {
        cwd?: string;
        env?: any;
        encoding?: string;
    }): ChildProcess;
    export function execSync(command: string, options?: {
        cwd?: string;
        input?: string|Buffer;
        stdio?: any;
        env?: any;
        uid?: number;
        gid?: number;
        timeout?: number;
        maxBuffer?: number;
        killSignal?: string;
        encoding?: string;
    }): ChildProcess;
    export function execFileSync(command: string, args?: string[], options?: {
        cwd?: string;
        input?: string|Buffer;
        stdio?: any;
        env?: any;
        uid?: number;
        gid?: number;
        timeout?: number;
        maxBuffer?: number;
        killSignal?: string;
        encoding?: string;
    }): ChildProcess;
}

declare module "url" {
    export interface Url {
        href: string;
        protocol: string;
        auth: string;
        hostname: string;
        port: string;
        host: string;
        pathname: string;
        search: string;
        query: any; // string | Object
        slashes: boolean;
        hash?: string;
        path?: string;
    }

    export interface UrlOptions {
        protocol?: string;
        auth?: string;
        hostname?: string;
        port?: string;
        host?: string;
        pathname?: string;
        search?: string;
        query?: any;
        hash?: string;
        path?: string;
    }

    export function parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url;
    export function format(url: UrlOptions): string;
    export function resolve(from: string, to: string): string;
}

declare module "dns" {
    export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string;
    export function lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string;
    export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) =>void ): string[];
    export function resolve(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
    export function resolve4(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
    export function resolve6(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
    export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
    export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
    export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
    export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
    export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];
    export function reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[];
}

declare module "net" {
    import stream = require("stream");

    export interface Socket extends stream.Duplex {
        // Extended base methods
        write(buffer: Buffer): boolean;
        write(buffer: Buffer, cb?: Function): boolean;
        write(str: string, cb?: Function): boolean;
        write(str: string, encoding?: string, cb?: Function): boolean;
        write(str: string, encoding?: string, fd?: string): boolean;

        connect(port: number, host?: string, connectionListener?: Function): void;
        connect(path: string, connectionListener?: Function): void;
        bufferSize: number;
        setEncoding(encoding?: string): void;
        write(data: any, encoding?: string, callback?: Function): void;
        destroy(): void;
        pause(): void;
        resume(): void;
        setTimeout(timeout: number, callback?: Function): void;
        setNoDelay(noDelay?: boolean): void;
        setKeepAlive(enable?: boolean, initialDelay?: number): void;
        address(): { port: number; family: string; address: string; };
        unref(): void;
        ref(): void;

        remoteAddress: string;
        remoteFamily: string;
        remotePort: number;
        localAddress: string;
        localPort: number;
        bytesRead: number;
        bytesWritten: number;

        // Extended base methods
        end(): void;
        end(buffer: Buffer, cb?: Function): void;
        end(str: string, cb?: Function): void;
        end(str: string, encoding?: string, cb?: Function): void;
        end(data?: any, encoding?: string): void;
    }

    export var Socket: {
        new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket;
    };

    export interface Server extends Socket {
        listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server;
        listen(path: string, listeningListener?: Function): Server;
        listen(handle: any, listeningListener?: Function): Server;
        close(callback?: Function): Server;
        address(): { port: number; family: string; address: string; };
        maxConnections: number;
        connections: number;
    }
    export function createServer(connectionListener?: (socket: Socket) =>void ): Server;
    export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) =>void ): Server;
    export function connect(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): Socket;
    export function connect(port: number, host?: string, connectionListener?: Function): Socket;
    export function connect(path: string, connectionListener?: Function): Socket;
    export function createConnection(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): Socket;
    export function createConnection(port: number, host?: string, connectionListener?: Function): Socket;
    export function createConnection(path: string, connectionListener?: Function): Socket;
    export function isIP(input: string): number;
    export function isIPv4(input: string): boolean;
    export function isIPv6(input: string): boolean;
}

declare module "dgram" {
    import events = require("events");

    interface RemoteInfo {
        address: string;
        port: number;
        size: number;
    }

    interface AddressInfo {
        address: string;
        family: string;
        port: number;
    }

    export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket;

    interface Socket extends events.EventEmitter {
        send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void;
        bind(port: number, address?: string, callback?: () => void): void;
        close(): void;
        address(): AddressInfo;
        setBroadcast(flag: boolean): void;
        setMulticastTTL(ttl: number): void;
        setMulticastLoopback(flag: boolean): void;
        addMembership(multicastAddress: string, multicastInterface?: string): void;
        dropMembership(multicastAddress: string, multicastInterface?: string): void;
    }
}

declare module "fs" {
    import stream = require("stream");
    import events = require("events");

    interface Stats {
        isFile(): boolean;
        isDirectory(): boolean;
        isBlockDevice(): boolean;
        isCharacterDevice(): boolean;
        isSymbolicLink(): boolean;
        isFIFO(): boolean;
        isSocket(): boolean;
        dev: number;
        ino: number;
        mode: number;
        nlink: number;
        uid: number;
        gid: number;
        rdev: number;
        size: number;
        blksize: number;
        blocks: number;
        atime: Date;
        mtime: Date;
        ctime: Date;
    }

    interface FSWatcher extends events.EventEmitter {
        close(): void;
    }

    export interface ReadStream extends stream.Readable {
        close(): void;
    }
    export interface WriteStream extends stream.Writable {
        close(): void;
        bytesWritten: number;
    }

    /**
     * Asynchronous rename.
     * @param oldPath
     * @param newPath
     * @param callback No arguments other than a possible exception are given to the completion callback.
     */
    export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
    /**
     * Synchronous rename
     * @param oldPath
     * @param newPath
     */
    export function renameSync(oldPath: string, newPath: string): void;
    export function truncate(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
    export function truncate(path: string, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
    export function truncateSync(path: string, len?: number): void;
    export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
    export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
    export function ftruncateSync(fd: number, len?: number): void;
    export function chown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
    export function chownSync(path: string, uid: number, gid: number): void;
    export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
    export function fchownSync(fd: number, uid: number, gid: number): void;
    export function lchown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
    export function lchownSync(path: string, uid: number, gid: number): void;
    export function chmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
    export function chmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
    export function chmodSync(path: string, mode: number): void;
    export function chmodSync(path: string, mode: string): void;
    export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
    export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
    export function fchmodSync(fd: number, mode: number): void;
    export function fchmodSync(fd: number, mode: string): void;
    export function lchmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
    export function lchmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
    export function lchmodSync(path: string, mode: number): void;
    export function lchmodSync(path: string, mode: string): void;
    export function stat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void;
    export function lstat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void;
    export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void;
    export function statSync(path: string): Stats;
    export function lstatSync(path: string): Stats;
    export function fstatSync(fd: number): Stats;
    export function link(srcpath: string, dstpath: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
    export function linkSync(srcpath: string, dstpath: string): void;
    export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
    export function symlinkSync(srcpath: string, dstpath: string, type?: string): void;
    export function readlink(path: string, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void;
    export function readlinkSync(path: string): string;
    export function realpath(path: string, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void;
    export function realpath(path: string, cache: {[path: string]: string}, callback: (err: NodeJS.ErrnoException, resolvedPath: string) =>any): void;
    export function realpathSync(path: string, cache?: { [path: string]: string }): string;
    /*
     * Asynchronous unlink - deletes the file specified in {path}
     *
     * @param path
     * @param callback No arguments other than a possible exception are given to the completion callback.
     */
    export function unlink(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
    /*
     * Synchronous unlink - deletes the file specified in {path}
     *
     * @param path
     */
    export function unlinkSync(path: string): void;
    /*
     * Asynchronous rmdir - removes the directory specified in {path}
     *
     * @param path
     * @param callback No arguments other than a possible exception are given to the completion callback.
     */
    export function rmdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
    /*
     * Synchronous rmdir - removes the directory specified in {path}
     *
     * @param path
     */
    export function rmdirSync(path: string): void;
    /*
     * Asynchronous mkdir - creates the directory specified in {path}.  Parameter {mode} defaults to 0777.
     *
     * @param path
     * @param callback No arguments other than a possible exception are given to the completion callback.
     */
    export function mkdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
    /*
     * Asynchronous mkdir - creates the directory specified in {path}.  Parameter {mode} defaults to 0777.
     *
     * @param path
     * @param mode
     * @param callback No arguments other than a possible exception are given to the completion callback.
     */
    export function mkdir(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
    /*
     * Asynchronous mkdir - creates the directory specified in {path}.  Parameter {mode} defaults to 0777.
     *
     * @param path
     * @param mode
     * @param callback No arguments other than a possible exception are given to the completion callback.
     */
    export function mkdir(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void;
    /*
     * Synchronous mkdir - creates the directory specified in {path}.  Parameter {mode} defaults to 0777.
     *
     * @param path
     * @param mode
     * @param callback No arguments other than a possible exception are given to the completion callback.
     */
    export function mkdirSync(path: string, mode?: number): void;
    /*
     * Synchronous mkdir - creates the directory specified in {path}.  Parameter {mode} defaults to 0777.
     *
     * @param path
     * @param mode
     * @param callback No arguments other than a possible exception are given to the completion callback.
     */
    export function mkdirSync(path: string, mode?: string): void;
    export function readdir(path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void;
    export function readdirSync(path: string): string[];
    export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
    export function closeSync(fd: number): void;
    export function open(path: string, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void;
    export function open(path: string, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void;
    export function open(path: string, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void;
    export function openSync(path: string, flags: string, mode?: number): number;
    export function openSync(path: string, flags: string, mode?: string): number;
    export function utimes(path: string, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
    export function utimes(path: string, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void;
    export function utimesSync(path: string, atime: number, mtime: number): void;
    export function utimesSync(path: string, atime: Date, mtime: Date): void;
    export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
    export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void;
    export function futimesSync(fd: number, atime: number, mtime: number): void;
    export function futimesSync(fd: number, atime: Date, mtime: Date): void;
    export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
    export function fsyncSync(fd: number): void;
    export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void;
    export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number;
    export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void;
    export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number;
    /*
     * Asynchronous readFile - Asynchronously reads the entire contents of a file.
     *
     * @param fileName
     * @param encoding
     * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file.
     */
    export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void;
    /*
     * Asynchronous readFile - Asynchronously reads the entire contents of a file.
     *
     * @param fileName
     * @param options An object with optional {encoding} and {flag} properties.  If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer.
     * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file.
     */
    export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void;
    /*
     * Asynchronous readFile - Asynchronously reads the entire contents of a file.
     *
     * @param fileName
     * @param options An object with optional {encoding} and {flag} properties.  If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer.
     * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file.
     */
    export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void;
    /*
     * Asynchronous readFile - Asynchronously reads the entire contents of a file.
     *
     * @param fileName
     * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file.
     */
    export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void;
    /*
     * Synchronous readFile - Synchronously reads the entire contents of a file.
     *
     * @param fileName
     * @param encoding
     */
    export function readFileSync(filename: string, encoding: string): string;
    /*
     * Synchronous readFile - Synchronously reads the entire contents of a file.
     *
     * @param fileName
     * @param options An object with optional {encoding} and {flag} properties.  If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer.
     */
    export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string;
    /*
     * Synchronous readFile - Synchronously reads the entire contents of a file.
     *
     * @param fileName
     * @param options An object with optional {encoding} and {flag} properties.  If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer.
     */
    export function readFileSync(filename: string, options?: { flag?: string; }): Buffer;
    export function writeFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void;
    export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void;
    export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void;
    export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void;
    export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void;
    export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void;
    export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void;
    export function appendFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void;
    export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void;
    export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void;
    export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void;
    export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void;
    export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void;
    export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher;
    export function watch(filename: string, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher;
    export function exists(path: string, callback?: (exists: boolean) => void): void;
    export function existsSync(path: string): boolean;
    /** Constant for fs.access(). File is visible to the calling process. */
    export var F_OK: number;
    /** Constant for fs.access(). File can be read by the calling process. */
    export var R_OK: number;
    /** Constant for fs.access(). File can be written by the calling process. */
    export var W_OK: number;
    /** Constant for fs.access(). File can be executed by the calling process. */
    export var X_OK: number;
    /** Tests a user's permissions for the file specified by path. */
    export function access(path: string, callback: (err: NodeJS.ErrnoException) => void): void;
    export function access(path: string, mode: number, callback: (err: NodeJS.ErrnoException) => void): void;
    /** Synchronous version of fs.access. This throws if any accessibility checks fail, and does nothing otherwise. */
    export function accessSync(path: string, mode ?: number): void;
    export function createReadStream(path: string, options?: {
        flags?: string;
        encoding?: string;
        fd?: string;
        mode?: number;
        bufferSize?: number;
    }): ReadStream;
    export function createReadStream(path: string, options?: {
        flags?: string;
        encoding?: string;
        fd?: string;
        mode?: string;
        bufferSize?: number;
    }): ReadStream;
    export function createWriteStream(path: string, options?: {
        flags?: string;
        encoding?: string;
        string?: string;
    }): WriteStream;
}

declare module "path" {

    /**
     * A parsed path object generated by path.parse() or consumed by path.format().
     */
    export interface ParsedPath {
        /**
         * The root of the path such as '/' or 'c:\'
         */
        root: string;
        /**
         * The full directory path such as '/home/user/dir' or 'c:\path\dir'
         */
        dir: string;
        /**
         * The file name including extension (if any) such as 'index.html'
         */
        base: string;
        /**
         * The file extension (if any) such as '.html'
         */
        ext: string;
        /**
         * The file name without extension (if any) such as 'index'
         */
        name: string;
    }

    /**
     * Normalize a string path, reducing '..' and '.' parts.
     * 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.
     *
     * @param p string path to normalize.
     */
    export function normalize(p: string): string;
    /**
     * Join all arguments together and normalize the resulting path.
     * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.
     *
     * @param paths string paths to join.
     */
    export function join(...paths: any[]): string;
    /**
     * Join all arguments together and normalize the resulting path.
     * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.
     *
     * @param paths string paths to join.
     */
    export function join(...paths: string[]): string;
    /**
     * The right-most parameter is considered {to}.  Other parameters are considered an array of {from}.
     *
     * Starting from leftmost {from} paramter, resolves {to} to an absolute path.
     *
     * 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.
     *
     * @param pathSegments string paths to join.  Non-string arguments are ignored.
     */
    export function resolve(...pathSegments: any[]): string;
    /**
     * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory.
     *
     * @param path path to test.
     */
    export function isAbsolute(path: string): boolean;
    /**
     * Solve the relative path from {from} to {to}.
     * 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.
     *
     * @param from
     * @param to
     */
    export function relative(from: string, to: string): string;
    /**
     * Return the directory name of a path. Similar to the Unix dirname command.
     *
     * @param p the path to evaluate.
     */
    export function dirname(p: string): string;
    /**
     * Return the last portion of a path. Similar to the Unix basename command.
     * Often used to extract the file name from a fully qualified path.
     *
     * @param p the path to evaluate.
     * @param ext optionally, an extension to remove from the result.
     */
    export function basename(p: string, ext?: string): string;
    /**
     * Return the extension of the path, from the last '.' to end of string in the last portion of the path.
     * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string
     *
     * @param p the path to evaluate.
     */
    export function extname(p: string): string;
    /**
     * The platform-specific file separator. '\\' or '/'.
     */
    export var sep: string;
    /**
     * The platform-specific file delimiter. ';' or ':'.
     */
    export var delimiter: string;
    /**
     * Returns an object from a path string - the opposite of format().
     *
     * @param pathString path to evaluate.
     */
    export function parse(pathString: string): ParsedPath;
    /**
     * Returns a path string from an object - the opposite of parse().
     *
     * @param pathString path to evaluate.
     */
    export function format(pathObject: ParsedPath): string;

    export module posix {
      export function normalize(p: string): string;
      export function join(...paths: any[]): string;
      export function resolve(...pathSegments: any[]): string;
      export function isAbsolute(p: string): boolean;
      export function relative(from: string, to: string): string;
      export function dirname(p: string): string;
      export function basename(p: string, ext?: string): string;
      export function extname(p: string): string;
      export var sep: string;
      export var delimiter: string;
      export function parse(p: string): ParsedPath;
      export function format(pP: ParsedPath): string;
    }

    export module win32 {
      export function normalize(p: string): string;
      export function join(...paths: any[]): string;
      export function resolve(...pathSegments: any[]): string;
      export function isAbsolute(p: string): boolean;
      export function relative(from: string, to: string): string;
      export function dirname(p: string): string;
      export function basename(p: string, ext?: string): string;
      export function extname(p: string): string;
      export var sep: string;
      export var delimiter: string;
      export function parse(p: string): ParsedPath;
      export function format(pP: ParsedPath): string;
    }
}

declare module "string_decoder" {
    export interface NodeStringDecoder {
        write(buffer: Buffer): string;
        detectIncompleteChar(buffer: Buffer): number;
    }
    export var StringDecoder: {
        new (encoding: string): NodeStringDecoder;
    };
}

declare module "tls" {
    import crypto = require("crypto");
    import net = require("net");
    import stream = require("stream");

    var CLIENT_RENEG_LIMIT: number;
    var CLIENT_RENEG_WINDOW: number;

    export interface TlsOptions {
        pfx?: any;   //string or buffer
        key?: any;   //string or buffer
        passphrase?: string;
        cert?: any;
        ca?: any;    //string or buffer
        crl?: any;   //string or string array
        ciphers?: string;
        honorCipherOrder?: any;
        requestCert?: boolean;
        rejectUnauthorized?: boolean;
        NPNProtocols?: any;  //array or Buffer;
        SNICallback?: (servername: string) => any;
    }

    export interface ConnectionOptions {
        host?: string;
        port?: number;
        socket?: net.Socket;
        pfx?: any;   //string | Buffer
        key?: any;   //string | Buffer
        passphrase?: string;
        cert?: any;  //string | Buffer
        ca?: any;    //Array of string | Buffer
        rejectUnauthorized?: boolean;
        NPNProtocols?: any;  //Array of string | Buffer
        servername?: string;
    }

    export interface Server extends net.Server {
        // Extended base methods
        listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server;
        listen(path: string, listeningListener?: Function): Server;
        listen(handle: any, listeningListener?: Function): Server;

        listen(port: number, host?: string, callback?: Function): Server;
        close(): Server;
        address(): { port: number; family: string; address: string; };
        addContext(hostName: string, credentials: {
            key: string;
            cert: string;
            ca: string;
        }): void;
        maxConnections: number;
        connections: number;
    }

    export interface ClearTextStream extends stream.Duplex {
        authorized: boolean;
        authorizationError: Error;
        getPeerCertificate(): any;
        getCipher: {
            name: string;
            version: string;
        };
        address: {
            port: number;
            family: string;
            address: string;
        };
        remoteAddress: string;
        remotePort: number;
    }

    export interface SecurePair {
        encrypted: any;
        cleartext: any;
    }

    export interface SecureContextOptions {
        pfx?: any;   //string | buffer
        key?: any;   //string | buffer
        passphrase?: string;
        cert?: any;  // string | buffer
        ca?: any;    // string | buffer
        crl?: any;   // string | string[]
        ciphers?: string;
        honorCipherOrder?: boolean;
    }

    export interface SecureContext {
        context: any;
    }

    export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) =>void ): Server;
    export function connect(options: TlsOptions, secureConnectionListener?: () =>void ): ClearTextStream;
    export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream;
    export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream;
    export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair;
    export function createSecureContext(details: SecureContextOptions): SecureContext;
}

declare module "crypto" {
    export interface CredentialDetails {
        pfx: string;
        key: string;
        passphrase: string;
        cert: string;
        ca: any;    //string | string array
        crl: any;   //string | string array
        ciphers: string;
    }
    export interface Credentials { context?: any; }
    export function createCredentials(details: CredentialDetails): Credentials;
    export function createHash(algorithm: string): Hash;
    export function createHmac(algorithm: string, key: string): Hmac;
    export function createHmac(algorithm: string, key: Buffer): Hmac;
    interface Hash {
        update(data: any, input_encoding?: string): Hash;
        digest(encoding: 'buffer'): Buffer;
        digest(encoding: string): any;
        digest(): Buffer;
    }
    interface Hmac {
        update(data: any, input_encoding?: string): Hmac;
        digest(encoding: 'buffer'): Buffer;
        digest(encoding: string): any;
        digest(): Buffer;
    }
    export function createCipher(algorithm: string, password: any): Cipher;
    export function createCipheriv(algorithm: string, key: any, iv: any): Cipher;
    interface Cipher {
        update(data: Buffer): Buffer;
        update(data: string, input_encoding?: string, output_encoding?: string): string;
        final(): Buffer;
        final(output_encoding: string): string;
        setAutoPadding(auto_padding: boolean): void;
    }
    export function createDecipher(algorithm: string, password: any): Decipher;
    export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher;
    interface Decipher {
        update(data: Buffer): Buffer;
        update(data: string, input_encoding?: string, output_encoding?: string): string;
        final(): Buffer;
        final(output_encoding: string): string;
        setAutoPadding(auto_padding: boolean): void;
    }
    export function createSign(algorithm: string): Signer;
    interface Signer {
        update(data: any): void;
        sign(private_key: string, output_format: string): string;
    }
    export function createVerify(algorith: string): Verify;
    interface Verify {
        update(data: any): void;
        verify(object: string, signature: string, signature_format?: string): boolean;
    }
    export function createDiffieHellman(prime_length: number): DiffieHellman;
    export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman;
    interface DiffieHellman {
        generateKeys(encoding?: string): string;
        computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string;
        getPrime(encoding?: string): string;
        getGenerator(encoding: string): string;
        getPublicKey(encoding?: string): string;
        getPrivateKey(encoding?: string): string;
        setPublicKey(public_key: string, encoding?: string): void;
        setPrivateKey(public_key: string, encoding?: string): void;
    }
    export function getDiffieHellman(group_name: string): DiffieHellman;
    export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void;
    export function pbkdf2Sync(password: string, salt: string, iterations: number, keylen: number) : Buffer;
    export function randomBytes(size: number): Buffer;
    export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void;
    export function pseudoRandomBytes(size: number): Buffer;
    export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void;
}

declare module "stream" {
    import events = require("events");

    export interface Stream extends events.EventEmitter {
        pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T;
    }

    export interface ReadableOptions {
        highWaterMark?: number;
        encoding?: string;
        objectMode?: boolean;
    }

    export class Readable extends events.EventEmitter implements NodeJS.ReadableStream {
        readable: boolean;
        constructor(opts?: ReadableOptions);
        _read(size: number): void;
        read(size?: number): string|Buffer;
        setEncoding(encoding: string): void;
        pause(): void;
        resume(): void;
        pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T;
        unpipe<T extends NodeJS.WritableStream>(destination?: T): void;
        unshift(chunk: string): void;
        unshift(chunk: Buffer): void;
        wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream;
        push(chunk: any, encoding?: string): boolean;
    }

    export interface WritableOptions {
        highWaterMark?: number;
        decodeStrings?: boolean;
    }

    export class Writable extends events.EventEmitter implements NodeJS.WritableStream {
        writable: boolean;
        constructor(opts?: WritableOptions);
        _write(data: Buffer, encoding: string, callback: Function): void;
        _write(data: string, encoding: string, callback: Function): void;
        write(buffer: Buffer, cb?: Function): boolean;
        write(str: string, cb?: Function): boolean;
        write(str: string, encoding?: string, cb?: Function): boolean;
        end(): void;
        end(buffer: Buffer, cb?: Function): void;
        end(str: string, cb?: Function): void;
        end(str: string, encoding?: string, cb?: Function): void;
    }

    export interface DuplexOptions extends ReadableOptions, WritableOptions {
        allowHalfOpen?: boolean;
    }

    // Note: Duplex extends both Readable and Writable.
    export class Duplex extends Readable implements NodeJS.ReadWriteStream {
        writable: boolean;
        constructor(opts?: DuplexOptions);
        _write(data: Buffer, encoding: string, callback: Function): void;
        _write(data: string, encoding: string, callback: Function): void;
        write(buffer: Buffer, cb?: Function): boolean;
        write(str: string, cb?: Function): boolean;
        write(str: string, encoding?: string, cb?: Function): boolean;
        end(): void;
        end(buffer: Buffer, cb?: Function): void;
        end(str: string, cb?: Function): void;
        end(str: string, encoding?: string, cb?: Function): void;
    }

    export interface TransformOptions extends ReadableOptions, WritableOptions {}

    // Note: Transform lacks the _read and _write methods of Readable/Writable.
    export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream {
        readable: boolean;
        writable: boolean;
        constructor(opts?: TransformOptions);
        _transform(chunk: Buffer, encoding: string, callback: Function): void;
        _transform(chunk: string, encoding: string, callback: Function): void;
        _flush(callback: Function): void;
        read(size?: number): any;
        setEncoding(encoding: string): void;
        pause(): void;
        resume(): void;
        pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T;
        unpipe<T extends NodeJS.WritableStream>(destination?: T): void;
        unshift(chunk: string): void;
        unshift(chunk: Buffer): void;
        wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream;
        push(chunk: any, encoding?: string): boolean;
        write(buffer: Buffer, cb?: Function): boolean;
        write(str: string, cb?: Function): boolean;
        write(str: string, encoding?: string, cb?: Function): boolean;
        end(): void;
        end(buffer: Buffer, cb?: Function): void;
        end(str: string, cb?: Function): void;
        end(str: string, encoding?: string, cb?: Function): void;
    }

    export class PassThrough extends Transform {}
}

declare module "util" {
    export interface InspectOptions {
        showHidden?: boolean;
        depth?: number;
        colors?: boolean;
        customInspect?: boolean;
    }

    export function format(format: any, ...param: any[]): string;
    export function debug(string: string): void;
    export function error(...param: any[]): void;
    export function puts(...param: any[]): void;
    export function print(...param: any[]): void;
    export function log(string: string): void;
    export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string;
    export function inspect(object: any, options: InspectOptions): string;
    export function isArray(object: any): boolean;
    export function isRegExp(object: any): boolean;
    export function isDate(object: any): boolean;
    export function isError(object: any): boolean;
    export function inherits(constructor: any, superConstructor: any): void;
}

declare module "assert" {
    function internal (value: any, message?: string): void;
    module internal {
        export class AssertionError implements Error {
            name: string;
            message: string;
            actual: any;
            expected: any;
            operator: string;
            generatedMessage: boolean;

            constructor(options?: {message?: string; actual?: any; expected?: any;
                                  operator?: string; stackStartFunction?: Function});
        }

        export function fail(actual?: any, expected?: any, message?: string, operator?: string): void;
        export function ok(value: any, message?: string): void;
        export function equal(actual: any, expected: any, message?: string): void;
        export function notEqual(actual: any, expected: any, message?: string): void;
        export function deepEqual(actual: any, expected: any, message?: string): void;
        export function notDeepEqual(acutal: any, expected: any, message?: string): void;
        export function strictEqual(actual: any, expected: any, message?: string): void;
        export function notStrictEqual(actual: any, expected: any, message?: string): void;
        export var throws: {
            (block: Function, message?: string): void;
            (block: Function, error: Function, message?: string): void;
            (block: Function, error: RegExp, message?: string): void;
            (block: Function, error: (err: any) => boolean, message?: string): void;
        };

        export var doesNotThrow: {
            (block: Function, message?: string): void;
            (block: Function, error: Function, message?: string): void;
            (block: Function, error: RegExp, message?: string): void;
            (block: Function, error: (err: any) => boolean, message?: string): void;
        };

        export function ifError(value: any): void;
    }

    export = internal;
}

declare module "tty" {
    import net = require("net");

    export function isatty(fd: number): boolean;
    export interface ReadStream extends net.Socket {
        isRaw: boolean;
        setRawMode(mode: boolean): void;
    }
    export interface WriteStream extends net.Socket {
        columns: number;
        rows: number;
    }
}

declare module "domain" {
    import events = require("events");

    export class Domain extends events.EventEmitter {
        run(fn: Function): void;
        add(emitter: events.EventEmitter): void;
        remove(emitter: events.EventEmitter): void;
        bind(cb: (err: Error, data: any) => any): any;
        intercept(cb: (data: any) => any): any;
        dispose(): void;

        addListener(event: string, listener: Function): Domain;
        on(event: string, listener: Function): Domain;
        once(event: string, listener: Function): Domain;
        removeListener(event: string, listener: Function): Domain;
        removeAllListeners(event?: string): Domain;
    }

    export function create(): Domain;
}

declare module "constants" {
    export var E2BIG: number;
    export var EACCES: number;
    export var EADDRINUSE: number;
    export var EADDRNOTAVAIL: number;
    export var EAFNOSUPPORT: number;
    export var EAGAIN: number;
    export var EALREADY: number;
    export var EBADF: number;
    export var EBADMSG: number;
    export var EBUSY: number;
    export var ECANCELED: number;
    export var ECHILD: number;
    export var ECONNABORTED: number;
    export var ECONNREFUSED: number;
    export var ECONNRESET: number;
    export var EDEADLK: number;
    export var EDESTADDRREQ: number;
    export var EDOM: number;
    export var EEXIST: number;
    export var EFAULT: number;
    export var EFBIG: number;
    export var EHOSTUNREACH: number;
    export var EIDRM: number;
    export var EILSEQ: number;
    export var EINPROGRESS: number;
    export var EINTR: number;
    export var EINVAL: number;
    export var EIO: number;
    export var EISCONN: number;
    export var EISDIR: number;
    export var ELOOP: number;
    export var EMFILE: number;
    export var EMLINK: number;
    export var EMSGSIZE: number;
    export var ENAMETOOLONG: number;
    export var ENETDOWN: number;
    export var ENETRESET: number;
    export var ENETUNREACH: number;
    export var ENFILE: number;
    export var ENOBUFS: number;
    export var ENODATA: number;
    export var ENODEV: number;
    export var ENOENT: number;
    export var ENOEXEC: number;
    export var ENOLCK: number;
    export var ENOLINK: number;
    export var ENOMEM: number;
    export var ENOMSG: number;
    export var ENOPROTOOPT: number;
    export var ENOSPC: number;
    export var ENOSR: number;
    export var ENOSTR: number;
    export var ENOSYS: number;
    export var ENOTCONN: number;
    export var ENOTDIR: number;
    export var ENOTEMPTY: number;
    export var ENOTSOCK: number;
    export var ENOTSUP: number;
    export var ENOTTY: number;
    export var ENXIO: number;
    export var EOPNOTSUPP: number;
    export var EOVERFLOW: number;
    export var EPERM: number;
    export var EPIPE: number;
    export var EPROTO: number;
    export var EPROTONOSUPPORT: number;
    export var EPROTOTYPE: number;
    export var ERANGE: number;
    export var EROFS: number;
    export var ESPIPE: number;
    export var ESRCH: number;
    export var ETIME: number;
    export var ETIMEDOUT: number;
    export var ETXTBSY: number;
    export var EWOULDBLOCK: number;
    export var EXDEV: number;
    export var WSAEINTR: number;
    export var WSAEBADF: number;
    export var WSAEACCES: number;
    export var WSAEFAULT: number;
    export var WSAEINVAL: number;
    export var WSAEMFILE: number;
    export var WSAEWOULDBLOCK: number;
    export var WSAEINPROGRESS: number;
    export var WSAEALREADY: number;
    export var WSAENOTSOCK: number;
    export var WSAEDESTADDRREQ: number;
    export var WSAEMSGSIZE: number;
    export var WSAEPROTOTYPE: number;
    export var WSAENOPROTOOPT: number;
    export var WSAEPROTONOSUPPORT: number;
    export var WSAESOCKTNOSUPPORT: number;
    export var WSAEOPNOTSUPP: number;
    export var WSAEPFNOSUPPORT: number;
    export var WSAEAFNOSUPPORT: number;
    export var WSAEADDRINUSE: number;
    export var WSAEADDRNOTAVAIL: number;
    export var WSAENETDOWN: number;
    export var WSAENETUNREACH: number;
    export var WSAENETRESET: number;
    export var WSAECONNABORTED: number;
    export var WSAECONNRESET: number;
    export var WSAENOBUFS: number;
    export var WSAEISCONN: number;
    export var WSAENOTCONN: number;
    export var WSAESHUTDOWN: number;
    export var WSAETOOMANYREFS: number;
    export var WSAETIMEDOUT: number;
    export var WSAECONNREFUSED: number;
    export var WSAELOOP: number;
    export var WSAENAMETOOLONG: number;
    export var WSAEHOSTDOWN: number;
    export var WSAEHOSTUNREACH: number;
    export var WSAENOTEMPTY: number;
    export var WSAEPROCLIM: number;
    export var WSAEUSERS: number;
    export var WSAEDQUOT: number;
    export var WSAESTALE: number;
    export var WSAEREMOTE: number;
    export var WSASYSNOTREADY: number;
    export var WSAVERNOTSUPPORTED: number;
    export var WSANOTINITIALISED: number;
    export var WSAEDISCON: number;
    export var WSAENOMORE: number;
    export var WSAECANCELLED: number;
    export var WSAEINVALIDPROCTABLE: number;
    export var WSAEINVALIDPROVIDER: number;
    export var WSAEPROVIDERFAILEDINIT: number;
    export var WSASYSCALLFAILURE: number;
    export var WSASERVICE_NOT_FOUND: number;
    export var WSATYPE_NOT_FOUND: number;
    export var WSA_E_NO_MORE: number;
    export var WSA_E_CANCELLED: number;
    export var WSAEREFUSED: number;
    export var SIGHUP: number;
    export var SIGINT: number;
    export var SIGILL: number;
    export var SIGABRT: number;
    export var SIGFPE: number;
    export var SIGKILL: number;
    export var SIGSEGV: number;
    export var SIGTERM: number;
    export var SIGBREAK: number;
    export var SIGWINCH: number;
    export var SSL_OP_ALL: number;
    export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number;
    export var SSL_OP_CIPHER_SERVER_PREFERENCE: number;
    export var SSL_OP_CISCO_ANYCONNECT: number;
    export var SSL_OP_COOKIE_EXCHANGE: number;
    export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number;
    export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number;
    export var SSL_OP_EPHEMERAL_RSA: number;
    export var SSL_OP_LEGACY_SERVER_CONNECT: number;
    export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number;
    export var SSL_OP_MICROSOFT_SESS_ID_BUG: number;
    export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number;
    export var SSL_OP_NETSCAPE_CA_DN_BUG: number;
    export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number;
    export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number;
    export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number;
    export var SSL_OP_NO_COMPRESSION: number;
    export var SSL_OP_NO_QUERY_MTU: number;
    export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number;
    export var SSL_OP_NO_SSLv2: number;
    export var SSL_OP_NO_SSLv3: number;
    export var SSL_OP_NO_TICKET: number;
    export var SSL_OP_NO_TLSv1: number;
    export var SSL_OP_NO_TLSv1_1: number;
    export var SSL_OP_NO_TLSv1_2: number;
    export var SSL_OP_PKCS1_CHECK_1: number;
    export var SSL_OP_PKCS1_CHECK_2: number;
    export var SSL_OP_SINGLE_DH_USE: number;
    export var SSL_OP_SINGLE_ECDH_USE: number;
    export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number;
    export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number;
    export var SSL_OP_TLS_BLOCK_PADDING_BUG: number;
    export var SSL_OP_TLS_D5_BUG: number;
    export var SSL_OP_TLS_ROLLBACK_BUG: number;
    export var ENGINE_METHOD_DSA: number;
    export var ENGINE_METHOD_DH: number;
    export var ENGINE_METHOD_RAND: number;
    export var ENGINE_METHOD_ECDH: number;
    export var ENGINE_METHOD_ECDSA: number;
    export var ENGINE_METHOD_CIPHERS: number;
    export var ENGINE_METHOD_DIGESTS: number;
    export var ENGINE_METHOD_STORE: number;
    export var ENGINE_METHOD_PKEY_METHS: number;
    export var ENGINE_METHOD_PKEY_ASN1_METHS: number;
    export var ENGINE_METHOD_ALL: number;
    export var ENGINE_METHOD_NONE: number;
    export var DH_CHECK_P_NOT_SAFE_PRIME: number;
    export var DH_CHECK_P_NOT_PRIME: number;
    export var DH_UNABLE_TO_CHECK_GENERATOR: number;
    export var DH_NOT_SUITABLE_GENERATOR: number;
    export var NPN_ENABLED: number;
    export var RSA_PKCS1_PADDING: number;
    export var RSA_SSLV23_PADDING: number;
    export var RSA_NO_PADDING: number;
    export var RSA_PKCS1_OAEP_PADDING: number;
    export var RSA_X931_PADDING: number;
    export var RSA_PKCS1_PSS_PADDING: number;
    export var POINT_CONVERSION_COMPRESSED: number;
    export var POINT_CONVERSION_UNCOMPRESSED: number;
    export var POINT_CONVERSION_HYBRID: number;
    export var O_RDONLY: number;
    export var O_WRONLY: number;
    export var O_RDWR: number;
    export var S_IFMT: number;
    export var S_IFREG: number;
    export var S_IFDIR: number;
    export var S_IFCHR: number;
    export var S_IFLNK: number;
    export var O_CREAT: number;
    export var O_EXCL: number;
    export var O_TRUNC: number;
    export var O_APPEND: number;
    export var F_OK: number;
    export var R_OK: number;
    export var W_OK: number;
    export var X_OK: number;
    export var UV_UDP_REUSEADDR: number;
}


================================================
FILE: code/compiler/typings/tsd.d.ts
================================================
/// <reference path="node/node.d.ts" />


================================================
FILE: code/declarationspaces/declarationspace.js
================================================
var first;
(function (first) {
    var Foo = (function () {
        function Foo() {
        }
        return Foo;
    })();
    var foo;
    var bar;
    var bas;
})(first = exports.first || (exports.first = {}));
var second;
(function (second) {
    ;
    var bar = Bar;
})(second || (second = {}));
var third;
(function (third) {
    var Foo = (function () {
        function Foo() {
        }
        return Foo;
    })();
    var someVar = Foo;
    var someOtherVar = 123;
})(third || (third = {}));
var fourn;
(function (fourn) {
    var foo = 123;
    var bar;
})(fourn || (fourn = {}));
var meh;
(function (meh) {
    var something = {};
})(meh || (meh = {}));
var utility;
(function (utility) {
    function log(msg) {
        console.log(msg);
    }
    utility.log = log;
    function error(msg) {
        console.error(msg);
    }
    utility.error = error;
})(utility || (utility = {}));
utility.log('Call me');
utility.error('maybe!');
var importing;
(function (importing) {
    var Foo = (function () {
        function Foo() {
        }
        return Foo;
    })();
    var Bar = Foo;
    var bar;
})(importing || (importing = {}));
var importing;
(function (importing) {
    var Foo = (function () {
        function Foo() {
        }
        return Foo;
    })();
    importing.Foo = Foo;
})(importing || (importing = {}));
var Bar = importing.Foo;
var bar;
var typeofAnnotation;
(function (typeofAnnotation) {
    var foo = 123;
    var bar;
    bar = 456;
    bar = '789';
})(typeofAnnotation || (typeofAnnotation = {}));


================================================
FILE: code/declarationspaces/declarationspace.ts
================================================
export module first {
    class Foo { }
    interface Bar { }
    type Bas = {}

    var foo: Foo;
    var bar: Bar;
    var bas: Bas;
}

namespace second {
    interface Bar { };
    var bar = Bar; // ERROR: "cannot find name 'Bar'"
}

namespace third {
    class Foo { }
    var someVar = Foo;
    var someOtherVar = 123;
}

namespace fourn {
    var foo = 123;
    var bar: foo; // ERROR: "cannot find name 'foo'"
}


namespace meh {
    var something = {};
    // (function(something) {
    //     something.foo = 123;
    // })(something || something = {})
}

namespace utility {
    export function log(msg) {
        console.log(msg);
    }
    export function error(msg) {
        console.error(msg);
    }
}

// usage
utility.log('Call me');
utility.error('maybe!');


module importing {
    class Foo { }
    var Bar = Foo;
    var bar: Bar; // ERROR: "cannot find name 'Bar'"
}

namespace importing {
    export class Foo { }
}

import Bar = importing.Foo;
var bar: Bar; // Okay

namespace typeofAnnotation {
    var foo = 123;
    var bar: typeof foo; // `bar` has the same type as `foo` (here `number`)
    bar = 456; // Okay
    bar = '789'; // ERROR: Type `string` is not `assignable` to type `number`
}

================================================
FILE: code/dynamic-import-expressions/dynamicImportExpression.js
================================================
"use strict";
function myApp() {
    import(/* webpackChunkName: "momentjs" */ "moment")
        .then(function (moment) {
        // lazyModule has all of the proper types, autocomplete works,
        // type checking works, code references work \o/
        var time = moment().format();
        console.log("TypeScript >= 2.4.0 Dynamic Import Expression:");
        console.log(time);
    })
        .catch(function (err) {
        console.log("Failed to load moment", err);
    });
}


================================================
FILE: code/dynamic-import-expressions/dynamicImportExpression.ts
================================================

function myApp() {
    import(/* webpackChunkName: "momentjs" */ "moment")
        .then((moment) => {
            // lazyModule has all of the proper types, autocomplete works,
            // type checking works, code references work \o/
            const time = moment().format();
            console.log("TypeScript >= 2.4.0 Dynamic Import Expression:");
            console.log(time);
        })
        .catch((err) => {
            console.log("Failed to load moment", err);
        });
}


================================================
FILE: code/dynamic-import-expressions/package.json
================================================
{
  "name": "dynamic-import-expressions",
  "version": "1.0.0",
  "description": "",
  "main": "dynamicImportExpression.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Jose Quinto Zamora - https://blog.josequinto.com",
  "license": "ISC",
  "devDependencies": {
    "typescript": "^2.4.1"
  },
  "dependencies": {
    "moment": "^2.18.1"
  }
}


================================================
FILE: code/dynamic-import-expressions/tsconfig.json
================================================
{
    "compilerOptions": {
        "target": "es5",                          
        "module": "esnext",                     
        "lib": [
            "dom",
            "es5",
            "scripthost",
            "es2015.promise"
        ],                                        
        "strict": true,                           
        "moduleResolution": "node"            
    },
    "files": [
      "./dynamicImportExpression.ts"
  ]
}

================================================
FILE: code/errors/common-errors.ts
================================================
ga();

import {debounce} from "underscore";


================================================
FILE: code/errors/interpreting-errors.ts
================================================
export const module = 123;

type SomethingComplex = {
  foo: number,
  bar: string
}
function takeSomethingComplex(arg: SomethingComplex) {
}
function getBar(): string {
  return 'some bar';
}

//////////////////////////////////
// Example error production
//////////////////////////////////
const fail = {
  foo: 123,
  bar: getBar
};

takeSomethingComplex(fail); // TS ERROR HAPPENS HERE 


================================================
FILE: code/errors/tsconfig.json
================================================
{
  "compilerOptions": {
    "noEmit": true
  }
}


================================================
FILE: code/es6/classes/abstract.js
================================================
exports.foo = 123;
var Restable = (function () {
    function Restable() {
        this.abstract = toJSON();
    }
    return Restable;
})();


================================================
FILE: code/es6/classes/abstract.ts
================================================
export var foo = 123;

class Restable {
    abstract toJSON() : any;
}



================================================
FILE: code/es6/classes/class.js
================================================
var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var Point = (function () {
    function Point(x, y) {
        this.x = x;
        this.y = y;
    }
    Point.prototype.add = function (point) {
        return new Point(this.x + point.x, this.y + point.y);
    };
    return Point;
})();
var p1 = new Point(0, 10);
var p2 = new Point(10, 20);
var p3 = p1.add(p2);
var Point3D = (function (_super) {
    __extends(Point3D, _super);
    function Point3D(x, y, z) {
        _super.call(this, x, y);
        this.z = z;
    }
    Point3D.prototype.add = function (point) {
        var point2D = _super.prototype.add.call(this, point);
        return new Point3D(point2D.x, point2D.y, this.z + point.z);
    };
    return Point3D;
})(Point);
var Something = (function () {
    function Something() {
        Something.instances++;
    }
    Something.instances = 0;
    return Something;
})();
var s1 = new Something();
var s2 = new Something();
console.log(Something.instances);


================================================
FILE: code/es6/classes/class.ts
================================================
class Point {
    x: number;
    y: number;
    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }
    add(point: Point) {
        return new Point(this.x + point.x, this.y + point.y);
    }
}

var p1 = new Point(0, 10);
var p2 = new Point(10, 20);
var p3 = p1.add(p2); // {x:10,y:30}

class Point3D extends Point {
    z: number;
    constructor(x: number, y: number, z: number) {
        super(x, y);
        this.z = z;
    }
    add(point: Point3D) {
        var point2D = super.add(point);
        return new Point3D(point2D.x, point2D.y, this.z + point.z);
    }
}

class Something {
    static instances = 0;
    constructor() {
        Something.instances++;
    }
}

var s1 = new Something();
var s2 = new Something();
console.log(Something.instances); // 2


================================================
FILE: code/es6/classes/super.js
================================================
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
exports.foo = 123;
var asdf;
(function (asdf) {
    var Base = (function () {
        function Base() {
        }
        Base.prototype.log = function () { console.log('hello world'); };
        return Base;
    })();
    var Child = (function (_super) {
        __extends(Child, _super);
        function Child() {
            _super.apply(this, arguments);
        }
        Child.prototype.logWorld = function () { _super.prototype.log.call(this); };
        ;
        return Child;
    })(Base);
})(asdf || (asdf = {}));
var bse;
(function (bse) {
    var Base = (function () {
        function Base() {
            this.log = function () { console.log('hello world'); };
        }
        return Base;
    })();
    var Child = (function (_super) {
        __extends(Child, _super);
        function Child() {
            _super.apply(this, arguments);
        }
        Child.prototype.logWorld = function () { this.log(); };
        ;
        return Child;
    })(Base);
})(bse || (bse = {}));
var quz;
(function (quz) {
    var Base = (function () {
        function Base() {
            this.log = function () { console.log('hello world'); };
        }
        return Base;
    })();
    var Child = (function (_super) {
        __extends(Child, _super);
        function Child() {
            _super.apply(this, arguments);
        }
        Child.prototype.logWorld = function () { _super.prototype.log.call(this); };
        ;
        return Child;
    })(Base);
})(quz || (quz = {}));


================================================
FILE: code/es6/classes/super.ts
================================================
export var foo = 123;

module asdf {
    class Base {
        log() { console.log('hello world'); }
    }

    class Child extends Base {
        logWorld() { super.log() };
    }
}

module bse {
    class Base {
        log = () => { console.log('hello world'); }
    }

    class Child extends Base {
        logWorld() { this.log() };
    }
}

module quz {
    class Base {
        log = () => { console.log('hello world'); }
    }

    class Child extends Base {
        logWorld() { super.log() }; // ERROR : only `public` and `protected` methods of base class are accessible via `super`
    }
}

================================================
FILE: code/es6/classes/tsconfig.json
================================================
{
    "version": "1.4.1",
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "declaration": false,
        "noImplicitAny": false,
        "removeComments": true,
        "noLib": false
    },
    "filesGlob": [
        "./**/*.ts",
        "!./node_modules/**/*.ts"
    ],
    "files": [
        "./abstract.ts",
        "./class.ts",
        "./super.ts"
    ]
}


================================================
FILE: code/es6/const.js
================================================
exports.asdfasdfasfadf = 123;
var mustbeinit;
(function (mustbeinit) {
    var foo;
})(mustbeinit || (mustbeinit = {}));
var cantbechanged;
(function (cantbechanged) {
    var foo = 123;
    foo = 456;
})(cantbechanged || (cantbechanged = {}));
var block;
(function (block) {
    var foo = 123;
    if (true) {
        var foo_1 = 456;
    }
})(block || (block = {}));
var protectvariablereference;
(function (protectvariablereference) {
    var foo = { bar: 123 };
    foo = { bar: 456 };
})(protectvariablereference || (protectvariablereference = {}));
var noProtectDeep;
(function (noProtectDeep) {
    var foo = { bar: 123 };
    foo.bar = 456;
})(noProtectDeep || (noProtectDeep = {}));


================================================
FILE: code/es6/const.ts
================================================
export var asdfasdfasfadf = 123;


namespace mustbeinit {
    const foo;
}

namespace cantbechanged {
    const foo = 123;
    foo = 456;
}


namespace block {
    const foo = 123;
    if (true) {
        const foo = 456; // Allowed as its a new variable limited to this `if` block
    }
}


namespace protectvariablereference {
    const foo = { bar: 123 };
    foo = { bar: 456 }; // ERROR : Left hand side of an assignment expression cannot be a constant
}


namespace noProtectDeep {
    const foo = { bar: 123 };
    foo.bar = 456; // Allowed!
}


================================================
FILE: code/es6/destructuring.js
================================================
exports.destructuring = true;
var m1;
(function (m1) {
    var x = 1, y = 2;
    _a = [
        y,
        x
    ], x = _a[0], y = _a[1];
    console.log(x, y);
    var _a;
})(m1 || (m1 = {}));
var m2;
(function (m2) {
    var rect = {
        x: 0,
        y: 10,
        width: 15,
        height: 20
    };
    var x = rect.x, y = rect.y, width = rect.width, height = rect.height;
    console.log(x, y, width, height);
})(m2 || (m2 = {}));
var m3;
(function (m3) {
    var _a = [
        1,
        2,
        3,
        4
    ], x = _a[0], y = _a[1], remaining = _a.slice(2);
    console.log(x, y, remaining);
})(m3 || (m3 = {}));
var m3;
(function (m3) {
    var _a = [
        1,
        2,
        3,
        4
    ], x = _a[0], remaining = _a.slice(2);
    console.log(x, remaining);
})(m3 || (m3 = {}));


================================================
FILE: code/es6/destructuring.ts
================================================
export var destructuring = true;


module m1 {
    var x = 1, y = 2;
    [x, y] = [y, x];
    console.log(x, y); // 1,2
}

module m2 {
    var rect = { x: 0, y: 10, width: 15, height: 20 };
    var {x, y, width, height} = rect;
    console.log(x, y, width, height); // 0,10,15,20
}

module m3 {
    var [x, y, ...remaining] = [1, 2, 3, 4];
    console.log(x, y, remaining); // 1, 2, [3,4]
}

module m3 {
    var [x, , ...remaining] = [1, 2, 3, 4];
    console.log(x, remaining); // 1, [3,4]
}


================================================
FILE: code/es6/enums.js
================================================
"use strict";
exports.foo = 123;
var Color;
(function (Color) {
    Color[Color["Red"] = 0] = "Red";
    Color[Color["Green"] = 1] = "Green";
    Color[Color["Blue"] = 2] = "Blue";
})(Color || (Color = {}));
var Color;
(function (Color) {
    Color[Color["DarkRed"] = 3] = "DarkRed";
    Color[Color["DarkGreen"] = 4] = "DarkGreen";
    Color[Color["DarkBlue"] = 5] = "DarkBlue";
})(Color || (Color = {}));
var col = Color.Red;
col = 0;
var Tristate;
(function (Tristate) {
    Tristate[Tristate["False"] = 0] = "False";
    Tristate[Tristate["True"] = 1] = "True";
    Tristate[Tristate["Unknown"] = 2] = "Unknown";
})(Tristate || (Tristate = {}));
var lie = Tristate.False;
var AnimalFlags;
(function (AnimalFlags) {
    AnimalFlags[AnimalFlags["None"] = 0] = "None";
    AnimalFlags[AnimalFlags["HasClaws"] = 1] = "HasClaws";
    AnimalFlags[AnimalFlags["CanFly"] = 2] = "CanFly";
})(AnimalFlags || (AnimalFlags = {}));
function printAnimalAbilities(animal) {
    var animalFlags = animal.flags;
    if (animalFlags & AnimalFlags.HasClaws) {
        console.log('animal has claws');
    }
    if (animalFlags & AnimalFlags.CanFly) {
        console.log('animal can fly');
    }
    if (animalFlags == AnimalFlags.None) {
        console.log('nothing');
    }
}
var animal = { flags: AnimalFlags.None };
printAnimalAbilities(animal);
animal.flags |= AnimalFlags.HasClaws;
printAnimalAbilities(animal);
animal.flags &= ~AnimalFlags.HasClaws;
printAnimalAbilities(animal);
animal.flags |= AnimalFlags.HasClaws | AnimalFlags.CanFly;
printAnimalAbilities(animal);
var EnumsWithStatics;
(function (EnumsWithStatics) {
    var Weekday;
    (function (Weekday) {
        Weekday[Weekday["Monday"] = 0] = "Monday";
        Weekday[Weekday["Tuesday"] = 1] = "Tuesday";
        Weekday[Weekday["Wednesday"] = 2] = "Wednesday";
        Weekday[Weekday["Thursday"] = 3] = "Thursday";
        Weekday[Weekday["Friday"] = 4] = "Friday";
        Weekday[Weekday["Saturday"] = 5] = "Saturday";
        Weekday[Weekday["Sunday"] = 6] = "Sunday";
    })(Weekday || (Weekday = {}));
    var Weekday;
    (function (Weekday) {
        function isBusinessDay(day) {
            switch (day) {
                case Weekday.Saturday:
                case Weekday.Sunday:
                    return false;
                default:
                    return true;
            }
        }
        Weekday.isBusinessDay = isBusinessDay;
    })(Weekday || (Weekday = {}));
    var mon = Weekday.Monday;
    var sun = Weekday.Sunday;
    console.log(Weekday.isBusinessDay(mon));
    console.log(Weekday.isBusinessDay(sun));
})(EnumsWithStatics || (EnumsWithStatics = {}));


================================================
FILE: code/es6/enums.ts
================================================
export const foo = 123;

enum Color {
    Red,
    Green,
    Blue
}

enum Color {
    DarkRed = 3,
    DarkGreen,
    DarkBlue
}

var col = Color.Red;
col = 0; // Effectively same as Color.Red


enum Tristate {
    False,
    True,
    Unknown
}

var lie = Tristate.False;

/*enum AnimalFlags {
    None           = 0,
    HasClaws       = 1 << 0,
    CanFly         = 1 << 1,
    EatsFish       = 1 << 2,
    Endangered     = 1 << 3
}*/

enum AnimalFlags {
    None           = 0,
    HasClaws       = 1 << 0,
    CanFly         = 1 << 1,
}

function printAnimalAbilities(animal) {
    var animalFlags = animal.flags;
    if (animalFlags & AnimalFlags.HasClaws) {
        console.log('animal has claws');
    }
    if (animalFlags & AnimalFlags.CanFly) {
        console.log('animal can fly');
    }
    if (animalFlags == AnimalFlags.None){
        console.log('nothing');
    }
}

var animal = { flags: AnimalFlags.None };
printAnimalAbilities(animal); // nothing
animal.flags |= AnimalFlags.HasClaws;
printAnimalAbilities(animal); // animal has claws
animal.flags &= ~AnimalFlags.HasClaws;
printAnimalAbilities(animal); // nothing
animal.flags |= AnimalFlags.HasClaws | AnimalFlags.CanFly;
printAnimalAbilities(animal); // animal has claws, animal can fly


namespace EnumsWithStatics {
    enum Weekday {
        Monday,
        Tuesday,
        Wednesday,
        Thursday,
        Friday,
        Saturday,
        Sunday
    }
    namespace Weekday {
        export function isBusinessDay(day: Weekday) {
            switch (day) {
                case Weekday.Saturday:
                case Weekday.Sunday:
                    return false;
                default:
                    return true;
            }
        }
    }

    const mon = Weekday.Monday;
    const sun = Weekday.Sunday;
    console.log(Weekday.isBusinessDay(mon)); // true
    console.log(Weekday.isBusinessDay(sun)); // false
}


================================================
FILE: code/es6/for..of.js
================================================
exports.forof = true;
var m0;
(function (m0) {
    var someArray = [
        9,
        2,
        5
    ];
    for (var item in someArray) {
        console.log(item);
    }
})(m0 || (m0 = {}));
var m1;
(function (m1) {
    var someArray = [
        9,
        2,
        5
    ];
    for (var _i = 0; _i < someArray.length; _i++) {
        var item = someArray[_i];
        console.log(item);
    }
})(m1 || (m1 = {}));
var m2;
(function (m2) {
    var hello = "is it me you're looking for?";
    for (var _i = 0; _i < hello.length; _i++) {
        var char = hello[_i];
        console.log(char);
    }
})(m2 || (m2 = {}));
var m2;
(function (m2) {
    var articleParagraphs = document.querySelectorAll("article > p");
    for (var _i = 0; _i < articleParagraphs.length; _i++) {
        var paragraph = articleParagraphs[_i];
        paragraph.classList.add("read");
    }
})(m2 || (m2 = {}));


================================================
FILE: code/es6/for..of.ts
================================================
export var forof = true;

module m0 {
    var someArray = [9, 2, 5];
    for (var item in someArray) {
        console.log(item);
    }
}

module m1 {
    var someArray = [9, 2, 5];
    for (var item of someArray) {
        console.log(item);
    }
}

module m2 {
    var hello = "is it me you're looking for?";
    for (var char of hello) {
        console.log(char); // is it me you're looking for?
    }
}

module m2 {
    let articleParagraphs = document.querySelectorAll("article > p");
    // Error: Nodelist is not an array type or a string type
    for (let paragraph of articleParagraphs) { 
        paragraph.classList.add("read");
    }
}

================================================
FILE: code/es6/forof.js
================================================
exports.forof = true;
var m0;
(function (m0) {
    var someArray = [
        9,
        2,
        5
    ];
    for (var item in someArray) {
        console.log(item);
    }
})(m0 || (m0 = {}));
var m1;
(function (m1) {
    var someArray = [
        9,
        2,
        5
    ];
    for (var _i = 0; _i < someArray.length; _i++) {
        var item = someArray[_i];
        console.log(item);
    }
})(m1 || (m1 = {}));
var m2;
(function (m2) {
    var hello = "is it me you're looking for?";
    for (var _i = 0; _i < hello.length; _i++) {
        var char = hello[_i];
        console.log(char);
    }
})(m2 || (m2 = {}));
var m2;
(function (m2) {
    var articleParagraphs = document.querySelectorAll("article > p");
    for (var _i = 0; _i < articleParagraphs.length; _i++) {
        var paragraph = articleParagraphs[_i];
        paragraph.classList.add("read");
    }
})(m2 || (m2 = {}));


================================================
FILE: code/es6/iterators.js
================================================
var Component = (function () {
    function Component(name) {
        this.name = name;
    }
    return Component;
}());
var Frame = (function () {
    function Frame(name, components) {
        this.name = name;
        this.components = components;
        this.pointer = 0;
    }
    Frame.prototype.next = function () {
        if (this.pointer < this.components.length) {
            return {
                done: false,
                value: this.components[this.pointer++]
            };
        }
        else
            return {
                done: true
            };
    };
    return Frame;
}());
var frame = new Frame("Door", [new Component("top"), new Component("bottom"), new Component("left"), new Component("right")]);
var iteratorResult1 = frame.next();
var iteratorResult2 = frame.next();
var iteratorResult3 = frame.next();
var iteratorResult4 = frame.next();
var iteratorResult5 = frame.next();
var component = iteratorResult1.value;


================================================
FILE: code/es6/iterators.ts
================================================
// The book's chapter describes usage of Iterators with ES6 target
// This example showing usage of iterators with ES5 target
//
// The example from the chapter should work in moderen browsers and Node
// with target ES5 if you add es6.d.ts to the project

class Component {
  constructor (public name: string) {}
}

class Frame {

  private pointer = 0;

  constructor(public name: string, public components: Component[]) {}

  public next(): {done: boolean, value?: Component} {
    if (this.pointer < this.components.length) {
      return {
        done: false,
        value: this.components[this.pointer++]
      }
    } else return {
      done: true
    }
  }

}

let frame = new Frame("Door", [new Component("top"), new Component("bottom"), new Component("left"), new Component("right")]);
let iteratorResult1 = frame.next(); //{ done: false, value: Component { name: 'top' } }
let iteratorResult2 = frame.next(); //{ done: false, value: Component { name: 'bottom' } }
let iteratorResult3 = frame.next(); //{ done: false, value: Component { name: 'left' } }
let iteratorResult4 = frame.next(); //{ done: false, value: Component { name: 'right' } }
let iteratorResult5 = frame.next(); //{ done: true }

//It is possible to access the value of iterator result via the value property:
let component = iteratorResult1.value; //Component { name: 'top' }


================================================
FILE: code/es6/let.js
================================================
exports.asdfasdfasfadf = 123;
var first;
(function (first) {
    var something = [
        1,
        2,
        3
    ];
})(first || (first = {}));
var second;
(function (second) {
    var foo = 123;
    if (true) {
        var foo = 456;
    }
    console.log(foo);
})(second || (second = {}));
var third;
(function (third) {
    var foo = 123;
    function test() {
        var foo = 456;
    }
    test();
    console.log(foo);
})(third || (third = {}));
var fourth;
(function (fourth) {
    var index = 0;
    var array = [
        1,
        2,
        3
    ];
    for (var _index = 0; _index < array.length; _index++) {
        console.log(array[_index]);
    }
    console.log(index);
})(fourth || (fourth = {}));
var fifth;
(function (fifth) {
    if (true) {
        var foo = 123;
    }
})(fifth || (fifth = {}));
var fifth;
(function (fifth) {
    var foo = '123';
    if (true) {
        var _foo = 123;
    }
})(fifth || (fifth = {}));
var closures;
(function (closures) {
    var funcs = [];
    for (var i = 0; i < 3; i++) {
        funcs.push(function () {
            console.log(i);
        });
    }
    for (var j = 0; j < 3; j++) {
        funcs[j]();
    }
})(closures || (closures = {}));
var closures2;
(function (closures2) {
    var funcs = [];
    for (var i = 0; i < 3; i++) {
        (function () {
            var local = i;
            funcs.push(function () {
                console.log(local);
            });
        })();
    }
    for (var j = 0; j < 3; j++) {
        funcs[j]();
    }
})(closures2 || (closures2 = {}));
var closures3;
(function (closures3) {
    var funcs = [];
    for (var i = 0; i < 3; i++) {
        funcs.push(function () {
            console.log(i);
        });
    }
    for (var j = 0; j < 3; j++) {
        funcs[j]();
    }
})(closures3 || (closures3 = {}));


================================================
FILE: code/es6/let.ts
================================================
export var asdfasdfasfadf = 123;

module first {
    let something = [1, 2, 3];


}

module second {
    var foo = 123;
    if (true) {
        var foo = 456;
    }
    console.log(foo); // 456
}

module third {
    var foo = 123;
    function test() {
        var foo = 456;
    }
    test();
    console.log(foo); // 123
}

module fourth {
    var index = 0;
    var array = [1, 2, 3];
    for (let index = 0; index < array.length; index++) {
        console.log(array[index]);
    }
    console.log(index); // 0
}

module fifth {
    if (true) {
        let foo = 123;
    }
}

module fifth {
    var foo = '123';
    if (true) {
        let foo = 123;
    }
}

module closures {
    var funcs = [];
    // create a bunch of functions
    for (var i = 0; i < 3; i++) {
        funcs.push(function() {
            console.log(i);
        })
    }
    // call them
    for (var j = 0; j < 3; j++) {
        funcs[j]();
    }
}

module closures2 {
    var funcs = [];
    // create a bunch of functions
    for (var i = 0; i < 3; i++) {
        (function() {
            var local = i;
            funcs.push(function() {
                console.log(local);
            })
        })();
    }
    // call them
    for (var j = 0; j < 3; j++) {
        funcs[j]();
    }
}

module closures3 {
    var funcs = [];
    // create a bunch of functions
    for (let i = 0; i < 3; i++) { // Error : loop contains 
        funcs.push(function() {
            console.log(i);
        })
    }
    // call them
    for (var j = 0; j < 3; j++) {
        funcs[j]();
    }
}

================================================
FILE: code/es6/rest-parameters.js
================================================
var rest;
(function (rest) {
    function iTakeItAll(first, second) {
        var allOthers = [];
        for (var _i = 2; _i < arguments.length; _i++) {
            allOthers[_i - 2] = arguments[_i];
        }
        console.log(allOthers);
    }
    iTakeItAll('foo', 'bar');
    iTakeItAll('foo', 'bar', 'bas', 'qux');
})(rest = exports.rest || (exports.rest = {}));


================================================
FILE: code/es6/rest-parameters.ts
================================================
export module rest {
    function iTakeItAll(first, second, ...allOthers) {
        console.log(allOthers);
    }
    iTakeItAll('foo', 'bar'); // []
    iTakeItAll('foo', 'bar', 'bas', 'qux'); // ['bas','qux']    
}

================================================
FILE: code/es6/spread-operator.js
================================================
var spread;
(function (spread) {
    var list = [
        1,
        2
    ];
    list = list.concat([3, 4]);
})(spread = exports.spread || (exports.spread = {}));


================================================
FILE: code/es6/spread-operator.ts
================================================
export module spread {
    var list = [1, 2];
    list = [...list, 3, 4];
}

================================================
FILE: code/es6/template-strings.js
================================================
exports.templateStrings = '123';
var m1;
(function (m1) {
    var lyrics = "Never gonna give you up \
\nNever gonna let you down";
    console.log(lyrics);
})(m1 || (m1 = {}));
var m2;
(function (m2) {
    var lyrics = "Never gonna give you up\nNever gonna let you down";
    console.log(lyrics);
})(m2 || (m2 = {}));
var m3;
(function (m3) {
    var lyrics = 'Never gonna give you up';
    var html = '<div>' + lyrics + '</div>';
})(m3 || (m3 = {}));
var m4;
(function (m4) {
    var lyrics = 'Never gonna give you up';
    var html = "<div>" + lyrics + "</div>";
})(m4 || (m4 = {}));
var m5;
(function (m5) {
    console.log("1 and 1 one make " + (1 + 1));
})(m5 || (m5 = {}));
var m6;
(function (m6) {
    var say = "a bird in hand > two in the bush";
    var html = (_a = ["<div> I would just like to say : ", "</div>"], _a.raw = ["<div> I would just like to say : ", "</div>"], htmlEscape(_a, say));
    function htmlEscape(literals) {
        var placeholders = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            placeholders[_i - 1] = arguments[_i];
        }
        var result = "";
        for (var i = 0; i < placeholders.length; i++) {
            result += literals[i];
            result += placeholders[i].replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
        }
        result += literals[literals.length - 1];
        return result;
    }
    console.log(html);
    var _a;
})(m6 || (m6 = {}));


================================================
FILE: code/es6/template-strings.ts
================================================
export var templateStrings = '123';

module m1 {
    var lyrics = "Never gonna give you up \
\nNever gonna let you down";
    console.log(lyrics);
}

module m2 {
    var lyrics = `Never gonna give you up
Never gonna let you down`;
    console.log(lyrics);
}

module m3 {
    var lyrics = 'Never gonna give you up';
    var html = '<div>' + lyrics + '</div>';
}

module m4 {
    var lyrics = 'Never gonna give you up';
    var html = `<div>${lyrics}</div>`;
}

module m5 {
    console.log(`1 and 1 one make ${1 + 1}`);
}

module m6 {
    var say = "a bird in hand > two in the bush";
    var html = htmlEscape `<div> I would just like to say : ${say}</div>`
    
    // a sample tag function
    function htmlEscape(literals, ...placeholders) {
        let result = "";

        // Interleave the literals with the placeholders
        for (let i = 0; i < placeholders.length; i++) {
            result += literals[i];
            result += placeholders[i]
                .replace(/&/g, '&amp;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#39;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;');
        }

        // add the last literal
        result += literals[literals.length - 1];
        return result;
    }
    console.log(html);
}

================================================
FILE: code/es6/test.js
================================================


================================================
FILE: code/es6/test.ts
================================================


================================================
FILE: code/es6/tsconfig.json
================================================
{}


================================================
FILE: code/javascript/closure.js
================================================
"use strict";
function outerFunction(arg) {
    var variableInOuterFunction = arg;
    function bar() {
        console.log(variableInOuterFunction);
    }
    bar();
}
outerFunction("hello closure");
var another;
(function (another) {
    function outerFunction(arg) {
        var variableInOuterFunction = arg;
        return function () {
            console.log(variableInOuterFunction);
        };
    }
    var innerFunction = outerFunction("hello closure!");
    innerFunction();
})(another = exports.another || (exports.another = {}));
var revealing;
(function (revealing) {
    function createCounter() {
        var val = 0;
        return {
            increment: function () { val++; },
            getVal: function () { return val; }
        };
    }
    var counter = createCounter();
    counter.increment();
    console.log(counter.getVal());
})(revealing = exports.revealing || (exports.revealing = {}));
var server;
(function (server) {
    server.on(function handler(req, res) {
        loadData(req.id).then(function (data) {
            res.send(data);
        });
    });
})(server = exports.server || (exports.server = {}));


================================================
FILE: code/javascript/closure.ts
================================================
function outerFunction(arg) {
    var variableInOuterFunction = arg;

    function bar() {
        console.log(variableInOuterFunction); // Access a variable from the outer scope
    }

    // Call the local function to demonstrate that it has access to arg
    bar();
}

outerFunction("hello closure"); // logs hello closure!


export namespace another {
    function outerFunction(arg) {
        var variableInOuterFunction = arg;
        return function() {
            console.log(variableInOuterFunction);
        }
    }

    var innerFunction = outerFunction("hello closure!");

    // Note the outerFunction has returned
    innerFunction(); // logs hello closure!
}


export namespace revealing {
    function createCounter() {
        let val = 0;
        return {
            increment() { val++ },
            getVal() { return val }
        }
    }

    let counter = createCounter();
    counter.increment();
    console.log(counter.getVal()); // 1
}

export namespace server {
    server.on(function handler(req, res) {
        loadData(req.id).then(function(data) {
            // the `res` has been closed over and is available
            res.send(data);
        })
    });
}


================================================
FILE: code/javascript/tsconfig.json
================================================
{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "isolatedModules": false,
        "jsx": "react",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "declaration": false,
        "noImplicitAny": false,
        "noImplicitUseStrict": false,
        "removeComments": true,
        "noLib": false,
        "preserveConstEnums": true,
        "suppressImplicitAnyIndexErrors": true
    },
    "exclude": [
        "node_modules",
        "typings/browser",
        "typings/browser.d.ts"
    ],
    "compileOnSave": true,
    "buildOnSave": false,
    "atom": {
        "rewriteTsconfig": false
    }
}


================================================
FILE: code/tips/bindIsBad.js
================================================
"use strict";
var Adder = (function () {
    function Adder(a) {
        this.a = a;
    }
    Adder.prototype.add = function (b) {
        return this.a + b;
    };
    return Adder;
})();
function useAdd(add) {
    return add(456);
}
var adder = new Adder('mary had a little 🐑');
useAdd(adder.add.bind(adder));
useAdd(function (x) { return adder.add(x); });
function twoParams(a, b) {
    return a + b;
}
var curryOne = twoParams.bind(null, 123);
curryOne(456);
curryOne('456');
var betterCurry;
(function (betterCurry) {
    function twoParams(a, b) {
        return a + b;
    }
    var curryOne = function (x) { return twoParams(123, x); };
    curryOne(456);
    curryOne('456');
})(betterCurry || (betterCurry = {}));


================================================
FILE: code/tips/bindIsBad.ts
================================================
export var _asdfasdfsadf;

class Adder {
    constructor(public a: string) { }

    add(b: string): string {
        return this.a + b;
    }
}

function useAdd(add: (x: number) => number) {
    return add(456);
}

let adder = new Adder('mary had a little 🐑');
useAdd(adder.add.bind(adder)); // No compile error!
useAdd((x) => adder.add(x)); // Error: number is not assignable to string


function twoParams(a: number, b: number) {
    return a + b;
}
let curryOne = twoParams.bind(null, 123);
curryOne(456); // Okay but is not type checked!
curryOne('456'); // Allowed because it wasn't type checked

namespace betterCurry {
    function twoParams(a: number, b: number) {
        return a + b;
    }
    let curryOne = (x: number) => twoParams(123, x);
    curryOne(456); // Okay and type checked!
    curryOne('456'); // Error!
}


================================================
FILE: code/tips/currying.js
================================================
"use strict";
var add = function (x) { return function (y) { return x + y; }; };
add(123)(456);
var add123 = add(123);
add123(456);


================================================
FILE: code/tips/currying.ts
================================================
export var _asdfasdfasdf;


// A function that supports currying
let add = (x: number) => (y: number) => x + y;

// Simple usage
add(123)(456);

// curried
let add123 = add(123);

// use the curried function
add123(456);


================================================
FILE: code/tips/lazyObjectLiteralInitialization.js
================================================
"use strict";
var JS;
(function (JS) {
    var foo = {};
    foo.bar = 123;
    foo.bas = "Hello World";
})(JS = exports.JS || (exports.JS = {}));
var TS;
(function (TS) {
    var foo = {
        bar: 123,
        bas: "Hello World",
    };
})(TS = exports.TS || (exports.TS = {}));
var TSQuick;
(function (TSQuick) {
    var foo = {};
    foo.bar = 123;
    foo.bas = "Hello World";
})(TSQuick = exports.TSQuick || (exports.TSQuick = {}));
var TSMiddle;
(function (TSMiddle) {
    var foo = {};
    foo.bar = 123;
    foo.bas = "Hello World";
    foo.bar = 'Hello Stranger';
})(TSMiddle = exports.TSMiddle || (exports.TSMiddle = {}));


================================================
FILE: code/tips/lazyObjectLiteralInitialization.ts
================================================
export namespace JS {
    let foo = {};
    foo.bar = 123;
    foo.bas = "Hello World";
}

export namespace TS {
    let foo = {
        bar: 123,
        bas: "Hello World",
    };
}

export namespace TSQuick {
    let foo = {} as any;
    foo.bar = 123;
    foo.bas = "Hello World";
}

export namespace TSMiddle {
    interface Foo {
        bar: number
        bas: string
    }

    let foo = {} as Foo;
    foo.bar = 123;
    foo.bas = "Hello World";

    // later in the codebase:
    foo.bar = 'Hello Stranger'; // Error: You probably misspelled `bas` as `bar`, cannot assign string to number
}


================================================
FILE: code/tips/mixins.js
================================================
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Disposable = (function () {
    function Disposable() {
    }
    Disposable.prototype.dispose = function () {
        this.isDisposed = true;
    };
    return Disposable;
})();
var Activatable = (function () {
    function Activatable() {
    }
    Activatable.prototype.activate = function () {
        this.isActive = true;
    };
    Activatable.prototype.deactivate = function () {
        this.isActive = false;
    };
    return Activatable;
})();
var ActivatibleDisposible = (function () {
    Disposable.apply(this);
    ActivatibleDisposible.apply(this);
    return this;
});
var SmartObject = (function (_super) {
    __extends(SmartObject, _super);
    function SmartObject() {
        var _this = this;
        _super.call(this);
        setInterval(function () { return console.log(_this.isActive + " : " + _this.isDisposed); }, 500);
    }
    SmartObject.prototype.interact = function () {
        this.activate();
    };
    return SmartObject;
})(ActivatibleDisposible);
applyMixins(SmartObject, [Disposable, Activatable]);
var smartObj = new SmartObject();
setTimeout(function () { return smartObj.interact(); }, 1000);
function applyMixins(derivedCtor, baseCtors) {
    baseCtors.forEach(function (baseCtor) {
        Object.getOwnPropertyNames(baseCtor.prototype).forEach(function (name) {
            derivedCtor.prototype[name] = baseCtor.prototype[name];
        });
    });
}


================================================
FILE: code/tips/mixins.ts
================================================
// Disposable Mixin
class Disposable {
    isDisposed: boolean;
    dispose() {
        this.isDisposed = true;
    }

}
 
// Activatable Mixin
class Activatable {
    isActive: boolean;
    activate() {
        this.isActive = true;
    }
    deactivate() {
        this.isActive = false;
    }
}

interface ActivatibleDisposible extends Disposable, Activatable {
    new (): ActivatibleDisposible;
}

var ActivatibleDisposible: ActivatibleDisposible = <any>(function(){
    Disposable.apply(this);
    ActivatibleDisposible.apply(this);
    return this;
})

class SmartObject extends ActivatibleDisposible {
    constructor() {
        super();
        setInterval(() => console.log(this.isActive + " : " + this.isDisposed), 500);
    }

    interact() {
        this.activate();
    }
}
applyMixins(SmartObject, [Disposable, Activatable])

var smartObj = new SmartObject();
setTimeout(() => smartObj.interact(), 1000);
 
////////////////////////////////////////
// In your runtime library somewhere
////////////////////////////////////////

function applyMixins(derivedCtor: any, baseCtors: any[]) {
    baseCtors.forEach(baseCtor => {
        Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
            derivedCtor.prototype[name] = baseCtor.prototype[name];
        })
    });
}

================================================
FILE: code/tips/nominalTyping.js
================================================
var EnumDriven;
(function (EnumDriven) {
    var FooIdBrand;
    (function (FooIdBrand) {
    })(FooIdBrand || (FooIdBrand = {}));
    var BarIdBrand;
    (function (BarIdBrand) {
    })(BarIdBrand || (BarIdBrand = {}));
    var fooId;
    var barId;
    fooId = barId;
    barId = fooId;
    fooId = 'foo';
    barId = 'bar';
    var str;
    str = fooId;
    str = barId;
})(EnumDriven || (EnumDriven = {}));
var Interface;
(function (Interface) {
    var fooId;
    var barId;
    fooId = barId;
    barId = fooId;
    fooId = barId;
    barId = fooId;
    fooId = 'foo';
    barId = 'bar';
    var str;
    str = fooId;
    str = barId;
})(Interface || (Interface = {}));


================================================
FILE: code/tips/nominalTyping.ts
================================================
namespace Literal {
  /** Generic Id type */
  type Id<T extends string> = {
    type: T,
    value: string,
  }

  /** Specific Id types */
  type FooId = Id<'foo'>;
  type BarId = Id<'bar'>;

  /** Optional: contructors functions */
  const createFoo = (value: string): FooId => ({ type: 'foo', value });
  const createBar = (value: string): BarId => ({ type: 'bar', value });

  let foo = createFoo('sample')
  let bar = createBar('sample');

  foo = bar; // Error
  foo = foo; // Okay
}

namespace EnumDriven {
  // FOO
  enum FooIdBrand { }
  type FooId = FooIdBrand & string;

  // BAR
  enum BarIdBrand { }
  type BarId = BarIdBrand & string;

  /**
   * Usage Demo
   */
  var fooId: FooId;
  var barId: BarId;

  // Safety!
  fooId = barId; // error
  barId = fooId; // error

  // Newing up
  fooId = 'foo' as FooId;
  barId = 'bar' as BarId;

  // Both types are compatible with the base
  var str: string;
  str = fooId;
  str = barId;
}

namespace Interface {

  // FOO
  interface FooId extends String {
    _fooIdBrand: string; // To prevent type errors
  }

  // BAR
  interface BarId extends String {
    _barIdBrand: string; // To prevent type errors
  }

  /**
   * Usage Demo
   */
  var fooId: FooId;
  var barId: BarId;

  // Safety!
  fooId = barId; // error
  barId = fooId; // error
  fooId = <FooId>barId; // error
  barId = <BarId>fooId; // error

  // Newing up
  fooId = 'foo' as any;
  barId = 'bar' as any;

  // If you need the base string
  var str: string;
  str = fooId as any;
  str = barId as any;
}


================================================
FILE: code/tips/statefulFunctions.js
================================================
var called = (new (function () {
    function class_1() {
        var _this = this;
        this.count = 0;
        this.called = function () {
            _this.count++;
            console.log("Called : " + _this.count);
        };
    }
    return class_1;
})()).called;
called();
called();


================================================
FILE: code/tips/statefulFunctions.ts
================================================
let {called} = new class {
    count = 0;
    called = () => {
        this.count++;
        console.log(`Called : ${this.count}`);
    }
};

called(); // Called : 1
called(); // Called : 2


================================================
FILE: code/tips/stringEnums.js
================================================
"use strict";
var Simple;
(function (Simple) {
    var Tristate = {
        False: '',
        True: '',
        Unknown: ''
    };
    Object.keys(Tristate).map(function (key) { return Tristate[key] = key; });
    var state = Tristate.True;
    if (state === Tristate.True) {
    }
})(Simple = exports.Simple || (exports.Simple = {}));
var Fancy;
(function (Fancy) {
    var state;
    state = 'False';
})(Fancy = exports.Fancy || (exports.Fancy = {}));


================================================
FILE: code/tips/stringEnums.ts
================================================
export namespace Simple {
    let Tristate = {
        False: '',
        True: '',
        Unknown: ''
    };

    // make values same as keys
    Object.keys(Tristate).map((key) => Tristate[key] = key);


    /**
     * Usage
     */

    // Assigning
    let state = Tristate.True;

    // Checking if it matches
    if (state === Tristate.True) {

    }
}


export namespace Fancy {
    type TriState = 'False' | 'True' | 'Unknown';

    let state: TriState;
    state = 'False';
}


================================================
FILE: code/tips/tsconfig.json
================================================
{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "declaration": false,
        "noImplicitAny": false,
        "removeComments": true,
        "moduleResolution": "node",
        "isolatedModules": false,
        "jsx": "react",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "noLib": false,
        "preserveConstEnums": true,
        "suppressImplicitAnyIndexErrors": true
    },
    "filesGlob": [
        "**/*.ts",
        "**/*.tsx",
        "!node_modules/**"
    ],
    "files": [
        "bindIsBad.ts",
        "currying.ts",
        "lazyObjectLiteralInitialization.ts",
        "mixins.ts",
        "nominalTyping.ts",
        "statefulFunctions.ts",
        "stringEnums.ts"
    ],
    "exclude": [],
    "atom": {
        "rewriteTsconfig": true
    }
}


================================================
FILE: code/types/assertion.js
================================================
exports.asdf = 123;
var porting;
(function (porting) {
    var foo = {};
    foo.bar = 123;
    foo.bas = 'hello';
})(porting || (porting = {}));
var assert;
(function (assert) {
    var foo = {};
    foo.bar = 123;
    foo.bas = 'hello';
})(assert || (assert = {}));
var sdfsdfsdf;
(function (sdfsdfsdf) {
    var foo;
    var bar = foo;
})(sdfsdfsdf || (sdfsdfsdf = {}));
var doubleAssertion;
(function (doubleAssertion) {
    function handler1(event) {
        var mouseEvent = event;
    }
    function handler2(event) {
        var element = event;
    }
    function handler(event) {
        var element = event;
    }
})(doubleAssertion || (doubleAssertion = {}));


================================================
FILE: code/types/assertion.ts
================================================
export var asdf = 123;

module porting {
    var foo = {};
    foo.bar = 123; // error : property 'bar' does not exist on `{}`
    foo.bas = 'hello'; // error : property 'bas' does not exist on `{}`
}

module assert {
    interface Foo {
        bar: number;
        bas: string;
    }
    var foo = {} as Foo;
    foo.bar = 123;
    foo.bas = 'hello';
}

module sdfsdfsdf {
    var foo: any;
    var bar = <string>foo; // bar is now of type "string"
}


namespace doubleAssertion {

    function handler1(event: Event) {
        let mouseEvent = event as MouseEvent;
    }

    function handler2(event: Event) {
        let element = event as HTMLElement; // Error : Neither 'Event' not type 'HTMLElement' is assignable to the other
    }

    function handler(event: Event) {
        let element = event as any as HTMLElement; // Okay!
    }
}


================================================
FILE: code/types/callable.ts
================================================
export namespace asdfasdfasdfasdflkjasdflkjasdflkjasdflkjasdf {
}

namespace A {
  interface ReturnString {
    (): string
  }
  declare const foo: ReturnString;
  const bar = foo(); // bar is inferred as a string
}

namespace Complex {
  interface Complex {
    (foo: string, bar?: number, ...others: boolean[]): number;
  }

  interface Overloaded {
    (foo: string): string
    (foo: number): number
  }

  // example implementation
  const overloaded: Overloaded = (foo) => foo;

  // example usage
  const str = overloaded(''); // str is inferred string
  const number = overloaded(123); // num is inferred number
}

namespace Direct {
  const overloaded: {
    (foo: string): string
    (foo: number): number
  } = (foo) => foo;

  const simple: (foo: number) => string
    = (foo) => foo.toString();

  interface CallMeWithNewToGetString {
    new(): string
  }
  // Usage 
  declare const Foo: CallMeWithNewToGetString;
  const bar = new Foo(); // bar is inferred to be of type string 
}



================================================
FILE: code/types/freshness/freshness.js
================================================
exports.foo = 123;
var first;
(function (first) {
    function logName(something) {
        console.log(something.name);
    }
    var person = { name: 'matt', job: 'being awesome' };
    var animal = { name: 'cow', diet: 'vegan, but has milk of own species' };
    var random = { note: "I don't have a name property" };
    logName(person);
    logName(animal);
    logName(random);
})(first || (first = {}));
var second;
(function (second) {
    function logName(something) {
        console.log(something.name);
    }
    logName({ name: 'matt' });
    logName({ name: 'matt', job: 'being awesome' });
})(second || (second = {}));
var second;
(function (second) {
    function logIfHasName(something) {
        if (something.name) {
            console.log(something.name);
        }
    }
    var person = { name: 'matt', job: 'being awesome' };
    var animal = { name: 'cow', diet: 'vegan, but has milk of own species' };
    var random = { note: "I don't have a name property" };
    logIfHasName(person);
    logIfHasName(animal);
    logIfHasName(random);
    logIfHasName({ neme: 'I just misspelled name to neme' });
})(second || (second = {}));


================================================
FILE: code/types/freshness/freshness.ts
================================================
export var foo = 123;

module first {
	function logName(something: { name: string }) {
		console.log(something.name);
	}

	var person = { name: 'matt', job: 'being awesome' };
	var animal = { name: 'cow', diet: 'vegan, but has milk of own species' };
	var random = { note: `I don't have a name property` };

	logName(person); // okay
	logName(animal); // okay
	logName(random); // Error : property `name` is missing
}

module second {
	function logName(something: { name: string }) {
		console.log(something.name);
	}

	logName({ name: 'matt' }); // okay
	logName({ name: 'matt', job: 'being awesome' }); // Error: object literals must only specify known properties. `job` is excessive here.
}

module third {
	function logIfHasName(something: { name?: string }) {
		if (something.name) {
			console.log(something.name);
		}
	}
	var person = { name: 'matt', job: 'being awesome' };
	var animal = { name: 'cow', diet: 'vegan, but has milk of own species' };

	logIfHasName(person); // okay
	logIfHasName(animal); // okay
	logIfHasName({ neme: 'I just misspelled name to neme' }); // Error: object literals must only specify known properties. `neme` is excessive here.
}

module fourth {
	var x: { foo: number; [x: string]: any };
	x = { foo: 1, baz: 2 }; // Ok, `baz` matched by index signature
}

module fifth {
	// Assuming
	interface State {
		foo: string;
		bar: string;
	}

	class MyComponent {
		state: any;

		setState(state: State) {
			/* ... */
		}

		doSomething() {
			// You want to do:
			this.setState({ foo: 'Hello' }); // Error: missing property bar

			// But because state contains both `foo` and `bar` TypeScript would force you to do:
			this.setState({ foo: 'Hello', bar: this.state.bar });
		}
	}
}

module sixth {
	// Assuming
	interface State {
		foo?: string;
		bar?: string;
	}

	class MyComponent {
		state: any;

		setState(state: State) {
			/* ... */
		}

		doSomething() {
			// You want to do:
			this.setState({ foo: 'Hello' }); // Yay works fine!

			// Because of freshness it's protected against typos as well!
			this.setState({ foos: 'Hello' }); // Error: Objects may only specify known properties

			// And still type checked
			this.setState({ foo: 123 }); // Error: Cannot assign number to a string
		}
	}
}


================================================
FILE: code/types/freshness/index-signatures.js
================================================
var a;
(function (a) {
    var foo = {};
    foo['Hello'] = 'World';
    console.log(foo['Hello']);
})(a || (a = {}));
var b;
(function (b) {
    var Foo = (function () {
        function Foo(message) {
            this.message = message;
        }
        ;
        Foo.prototype.log = function () {
            console.log(this.message);
        };
        return Foo;
    }());
    var foo = {};
    foo['Hello'] = new Foo('World');
    foo['Hello'].log();
})(b || (b = {}));
var c;
(function (c) {
    var obj = {
        toString: function () {
            console.log('toString called');
            return 'Hello';
        }
    };
    var foo = {};
    foo[obj] = 'World';
    console.log(foo[obj]);
    console.log(foo['Hello']);
})(c || (c = {}));
var d;
(function (d) {
    var foo = ['World'];
    console.log(foo[0]);
})(d || (d = {}));
var e;
(function (e) {
    var obj = {
        toString: function () {
            return 'Hello';
        }
    };
    var foo = {};
    foo[obj] = 'World';
    foo[obj.toString()] = 'World';
})(e || (e = {}));
var f;
(function (f) {
    var obj = { message: 'Hello' };
    var foo = {};
    foo[obj] = 'World';
    console.log(foo["[object Object]"]);
})(f || (f = {}));
var f;
(function (f) {
    console.log((1).toString());
    console.log((2).toString());
})(f || (f = {}));
var g;
(function (g) {
    var foo = {};
    foo['a'] = { message: 'some message' };
    foo['a'] = { messages: 'some message' };
    foo['a'].message;
    foo['a'].messages;
})(g || (g = {}));
var mustConform2;
(function (mustConform2) {
    var foo = { x: 1, y: 2 };
    foo['x'];
    var x = 'x';
    foo[x];
})(mustConform2 || (mustConform2 = {}));


================================================
FILE: code/types/freshness/index-signatures.ts
================================================
module a {
  let foo: any = {};
  foo['Hello'] = 'World';
  console.log(foo['Hello']); // World
}
module b {
  class Foo {
    constructor(public message: string) { };
    log() {
      console.log(this.message)
    }
  }

  let foo: any = {};
  foo['Hello'] = new Foo('World');
  foo['Hello'].log(); // World
}
module c {
  let obj = {
    toString() {
      console.log('toString called')
      return 'Hello'
    }
  }

  let foo: any = {};
  foo[obj] = 'World'; // toString called
  console.log(foo[obj]); // toString called, World
  console.log(foo['Hello']); // World
}

module d {
  let foo = ['World'];
  console.log(foo[0]); // World
}

module e {
  let obj = {
    toString() {
      return 'Hello'
    }
  }

  let foo: any = {};

  // ERROR: the index signature must be string, number ...
  foo[obj] = 'World';

  // FIX: TypeScript forces you to be explicit
  foo[obj.toString()] = 'World';
}

module f {
  let obj = { message: 'Hello' }
  let foo: any = {};

  // ERROR: the index signature must be string, number ...
  foo[obj] = 'World';

  // Here is what you actually stored!
  console.log(foo["[object Object]"]); // World
}

module f {
  console.log((1).toString()); // 1
  console.log((2).toString()); // 2
}

module g {
  let foo: { [index: string]: { message: string } } = {};

  /**
   * Must store stuff that conforms the structure
   */
  /** Ok */
  foo['a'] = { message: 'some message' };
  /** Error: must contain a `message` or type string. You have a typo in `message` */
  foo['a'] = { messages: 'some message' };

  /**
   * Stuff that is read is also type checked
   */
  /** Ok */
  foo['a'].message;
  /** Error: messages does not exist. You have a typo in `message` */
  foo['a'].messages;
}

module mustConform {

  /** Okay */
  interface Foo {
    [key: string]: number
    x: number;
    y: number;
  }
  /** Error */
  interface Bar {
    [key: string]: number
    x: number;
    y: string; // Property `y` must of of type number
  }
}

module mustConform2 {
  interface Foo {
    [key: string]: number
    x: number;
  }
  let foo: Foo = { x: 1, y: 2 };
  foo['x']; // number
  let x = 'x'
  foo[x]; // number
}

module dual {
  interface ArrStr {
    [key: string]: string | number; // Must accomodate all members

    [index: number]: string; // Can be a subset of string indexer

    // Just an example member
    length: number;
  }
}

module jsland {
  interface NestedCSS {
    color?: string;
    [selector: string]: string | NestedCSS;
  }

  const example: NestedCSS = {
    color: 'red',
    '.subclass': {
      color: 'blue'
    }
  }

  const failsSilently: NestedCSS = {
    colour: 'red', // No error as `colour` is a valid string selector
  }
}

module better {
  interface NestedCSS {
    color?: string;
    nest?: {
      [selector: string]: NestedCSS;
    }
  }

  const example: NestedCSS = {
    color: 'red',
    nest: {
      '.subclass': {
        color: 'blue'
      }
    }
  }

  const failsSilently: NestedCSS = {
    colour: 'red', // TS Error: unknown property `colour`
  }
}

================================================
FILE: code/types/freshness/tsconfig.json
================================================
{
    "version": "1.5.0-beta",
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "isolatedModules": false,
        "jsx": "react",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "declaration": false,
        "noImplicitAny": false,
        "removeComments": true,
        "noLib": false,
        "preserveConstEnums": true,
        "suppressImplicitAnyIndexErrors": true
    },
    "filesGlob": [
        "./**/*.ts",
        "./**/*.tsx",
        "!./node_modules/**/*"
    ],
    "files": [
        "./freshness.ts",
        "./index-signatures.ts"
    ],
    "atom": {
        "rewriteTsconfig": true
    }
}


================================================
FILE: code/types/functions.js
================================================
"use strict";
var parameter;
(function (parameter) {
    var sampleVariable;
    function foo(sampleParameter) { }
})(parameter || (parameter = {}));
var returnType;
(function (returnType) {
    function foo(sample) {
        return sample;
    }
})(returnType || (returnType = {}));
var inferred;
(function (inferred) {
    function foo(sample) {
        return sample;
    }
})(inferred || (inferred = {}));
var misspelled;
(function (misspelled) {
    function foo() {
        return { fou: 'John Doe' };
    }
    sendAsJSON(foo());
})(misspelled || (misspelled = {}));
var optional;
(function (optional) {
    function foo(bar, bas) {
    }
    foo(123);
    foo(123, 'hello');
})(optional || (optional = {}));
var optionalDefault;
(function (optionalDefault) {
    function foo(bar, bas) {
        if (bas === void 0) { bas = 'world'; }
        console.log(bar, bas);
    }
    foo(123);
    foo(123, 'hello');
})(optionalDefault || (optionalDefault = {}));
var overloads;
(function (overloads) {
    function padding(a, b, c, d) {
        if (b === undefined && c === undefined && d === undefined) {
            b = c = d = a;
        }
        else if (c === undefined && d === undefined) {
            c = a;
            d = b;
        }
        return {
            top: a,
            right: b,
            bottom: c,
            left: d
        };
    }
    overloads.padding = padding;
})(overloads || (overloads = {}));
var overloadsDone;
(function (overloadsDone) {
    function padding(a, b, c, d) {
        if (b === undefined && c === undefined && d === undefined) {
            b = c = d = a;
        }
        else if (c === undefined && d === undefined) {
            c = a;
            d = b;
        }
        return {
            top: a,
            right: b,
            bottom: c,
            left: d
        };
    }
    overloadsDone.padding = padding;
})(overloadsDone || (overloadsDone = {}));


================================================
FILE: code/types/functions.ts
================================================
export namespace asdfasdfasdfasdflkjasdflkjasdflkjasdflkjasdf {
}

namespace parameter {
    // variable annotation
    var sampleVariable: { bar: number }

    // function parameter
    function foo(sampleParameter: { bar: number }) { }
}

namespace returnType {
    interface Foo {
        foo: string;
    }

    // Return type annotated as `: Foo`
    function foo(sample: Foo) {
        return sample;
    }
}

namespace inferred {
    interface Foo {
        foo: string;
    }

    function foo(sample: Foo) {
        return sample; // inferred return type 'Foo'
    }
}

namespace misspelled {
    function foo() {
        return { fou: 'John Doe' }; // You might not find this misspelling `foo` till its too late
    }

    sendAsJSON(foo());
}

namespace optional {
    function foo(bar: number, bas?: string): void {
        // ..
    }

    foo(123);
    foo(123, 'hello');
}

namespace optionalDefault {
    function foo(bar: number, bas: string = 'world') {
        console.log(bar, bas);
    }

    foo(123);           // 123, world
    foo(123, 'hello');  // 123, hello
}

namespace overloads {
    export function padding(a: number, b?: number, c?: number, d?: any) {
        if (b === undefined && c === undefined && d === undefined) {
            b = c = d = a;
        }
        else if (c === undefined && d === undefined) {
            c = a;
            d = b;
        }
        return {
            top: a,
            right: b,
            bottom: c,
            left: d
        };
    }
}

namespace overloadsDone {
    export function padding(all: number);
    export function padding(topAndBottom: number, leftAndRight: number);
    export function padding(top: number, right: number, bottom: number, left: number);
    export function padding(a: number, b?: number, c?: number, d?: number) {
        if (b === undefined && c === undefined && d === undefined) {
            b = c = d = a;
        }
        else if (c === undefined && d === undefined) {
            c = a;
            d = b;
        }
        return {
            top: a,
            right: b,
            bottom: c,
            left: d
        };
    }
}


================================================
FILE: code/types/generics.js
================================================
var aaa;
(function (aaa) {
    var Queue = (function () {
        function Queue() {
            var _this = this;
            this.data = [];
            this.push = function (item) { return _this.data.push(item); };
            this.pop = function () { return _this.data.shift(); };
        }
        return Queue;
    }());
    var queue = new Queue();
    queue.push(0);
    queue.push("1");
    console.log(queue.pop().toPrecision(1));
    console.log(queue.pop().toPrecision(1));
})(aaa || (aaa = {}));
var bbb;
(function (bbb) {
    var QueueNumber = (function () {
        function QueueNumber() {
            var _this = this;
            this.data = [];
            this.push = function (item) { return _this.data.push(item); };
            this.pop = function () { return _this.data.shift(); };
        }
        return QueueNumber;
    }());
    var queue = new QueueNumber();
    queue.push(0);
    queue.push("1");
})(bbb || (bbb = {}));
var ccc;
(function (ccc) {
    var Queue = (function () {
        function Queue() {
            var _this = this;
            this.data = [];
            this.push = function (item) { return _this.data.push(item); };
            this.pop = function () { return _this.data.shift(); };
        }
        return Queue;
    }());
    var queue = new Queue();
    queue.push(0);
    queue.push("1");
})(ccc || (ccc = {}));


================================================
FILE: code/types/generics.ts
================================================
module aaa {
  class Queue {
    private data = [];
    push = (item) => this.data.push(item);
    pop = () => this.data.shift();
  }

  const queue = new Queue();
  queue.push(0);
  queue.push("1"); // Oops a mistake

  // a developer walks into a bar
  console.log(queue.pop().toPrecision(1));
  console.log(queue.pop().toPrecision(1)); // RUNTIME ERROR
}

module bbb {
  class QueueNumber {
    private data = [];
    push = (item: number) => this.data.push(item);
    pop = (): number => this.data.shift();
  }

  const queue = new QueueNumber();
  queue.push(0);
  queue.push("1"); // ERROR : cannot push a string. Only numbers allowed

  // ^ if that error is fixed the rest would be fine too
}

module ccc {
  /** A class definition with a generic parameter */
  class Queue<T> {
    private data = [];
    push = (item: T) => this.data.push(item);
    pop = (): T => this.data.shift();
  }

  /** Again sample usage */
  const queue = new Queue<number>();
  queue.push(0);
  queue.push("1"); // ERROR : cannot push a string. Only numbers allowed

  // ^ if that error is fixed the rest would be fine too
}

namespace ddd {
  const getJSON = <T>(config: {
    url: string,
    headers?: { [key: string]: string },
  }): Promise<T> => {
    const fetchConfig = ({
      method: 'GET',
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      ...(config.headers || {})
    });
    return fetch(config.url, fetchConfig)
      .then<T>(response => response.json());
  }

  type LoadUsersResponse = {
    users: {
      name: string;
      email: string;
    }[];
  };
  function loadUsers() {
    return getJSON<LoadUsersResponse>({ url: 'https://example.com/users' });
  }
}


================================================
FILE: code/types/interfaces.js
================================================
var Implement;
(function (Implement) {
    var MyPoint = (function () {
        function MyPoint() {
        }
        return MyPoint;
    }());
})(Implement || (Implement = {}));
var ErrorIt;
(function (ErrorIt) {
    var MyPoint = (function () {
        function MyPoint() {
        }
        return MyPoint;
    }());
})(ErrorIt || (ErrorIt = {}));


================================================
FILE: code/types/interfaces.ts
================================================
namespace Implement {
    interface Point {
        x: number; y: number;
    }

    class MyPoint implements Point {
        x: number; y: number; // Same as Point
    }
}

namespace ErrorIt {
    interface Point {
        x: number; y: number;
        z: number; // New member
    }

    class MyPoint implements Point { // ERROR : missing member `z`
        x: number; y: number;
    }
}


================================================
FILE: code/types/keyof.ts
================================================
namespace Test {
  const colors = {
    red: 'red',
    blue: 'blue'
  }
  type Colors = keyof typeof colors; 

  let color: Colors;
  color = 'red'; // okay
  color = 'blue'; // okay
  color = 'blue'; // Error
}

================================================
FILE: code/types/lib/exclude/nolibd.js
================================================
var foo = 123;
var bar = foo.toString();


================================================
FILE: code/types/lib/exclude/nolibd.ts
================================================
var foo = 123; 
var bar = foo.toString(); // Property 'toString' does not exist on type 'number'.

================================================
FILE: code/types/lib/exclude/tsconfig.json
================================================
{
    "compilerOptions":{
        "noLib": true
    }
}

================================================
FILE: code/types/lib/usage/libd.js
================================================
var foo = 123;
var bar = foo.toString();
var test = window;
window.helloWorld = function () { return console.log('hello world'); };
window.helloWorld();
Math.seedrandom();
Date.parse;
String.prototype.endsWith = function (suffix) {
    var str = this;
    return str && str.indexOf(suffix, str.length - suffix.length) !== -1;
};
console.log('foo bar'.endsWith('bas'));
console.log('foo bas'.endsWith('bas'));


================================================
FILE: code/types/lib/usage/libd.ts
================================================
var foo = 123;
var bar = foo.toString();

var test = window;

interface Window {
    helloWorld(): void;
}

// Add it at runtime
window.helloWorld = () => console.log('hello world');
// Call it
window.helloWorld();
// Misuse it and you get an error: 
// window.helloWorld('gracius'); // Error: Supplied parameters do not match the signature of the call target


interface Math {
    seedrandom(seed?: string);
}

Math.seedrandom();

Date.parse
interface Date {

}

interface String {
    endsWith(suffix: string): boolean;
}

String.prototype.endsWith = function(suffix: string): boolean {
    var str: string = this;
    return str && str.indexOf(suffix, str.length - suffix.length) !== -1;
}

console.log('foo bar'.endsWith('bas')); // false
console.log('foo bas'.endsWith('bas')); // true

================================================
FILE: code/types/lib/usage/tsconfig.json
================================================
{
    "compilerOptions":{
    }
}

================================================
FILE: code/types/libd.js
================================================


================================================
FILE: code/types/literal-types.js
================================================
"use strict";
var Simple;
(function (Simple) {
    var foo;
    foo = 'Bar';
})(Simple = exports.Simple || (exports.Simple = {}));
var Union;
(function (Union) {
    function move(distance, direction) {
    }
    move(1, "North");
    move(1, "Nurth");
})(Union = exports.Union || (exports.Union = {}));


================================================
FILE: code/types/literal-types.ts
================================================
export namespace Simple {
  let foo: 'Hello';
  foo = 'Bar'; // Error: "Bar" is not assignable to type "Hello"
}


export namespace Union {
  type CardinalDirection =
    "North"
    | "East"
    | "South"
    | "West";

  function move(distance: number, direction: CardinalDirection) {
    // ...
  }

  move(1, "North"); // Okay
  move(1, "Nurth"); // Error!
}

namespace StringEnum {

  /** Utility function to create a K:V from a list of strings */
  function strEnum<T extends string>(o: Array<T>): {[K in T]: K} {
    return o.reduce((res, key) => {
      res[key] = key;
      return res;
    }, Object.create(null));
  }

  /**
   * Sample create a string enum
   */

  /** Create a K:V */
  const Direction = strEnum([
    'North',
    'South',
    'East',
    'West'
  ])
  /** Create a Type */
  type Direction = keyof typeof Direction;

  /** 
   * Sample using a string enum
   */
  let sample: Direction;

  sample = Direction.North; // Okay
  sample = 'North'; // Okay
  sample = 'AnythingElse'; // ERROR!
}

================================================
FILE: code/types/migrating/migrating.js
================================================


================================================
FILE: code/types/migrating/migrating.ts
================================================
declare var $: any;
declare type JQuery = any;

================================================
FILE: code/types/migrating/tsconfig.json
================================================
{}

================================================
FILE: code/types/readonly.js
================================================
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Simple;
(function (Simple) {
    function foo(config) {
    }
    var config = { bar: 123, bas: 123 };
    foo(config);
})(Simple = exports.Simple || (exports.Simple = {}));
var Type;
(function (Type) {
    var foo = { bar: 123, bas: 456 };
    foo.bar = 456;
})(Type = exports.Type || (exports.Type = {}));
var Class;
(function (Class) {
    var Foo = (function () {
        function Foo() {
            this.bar = 1;
            this.baz = "hello";
        }
        return Foo;
    }());
})(Class = exports.Class || (exports.Class = {}));
var ReactEx;
(function (ReactEx) {
    ;
    var Something = (function (_super) {
        __extends(Something, _super);
        function Something() {
            _super.apply(this, arguments);
        }
        return Something;
    }(React.Component));
    ReactEx.Something = Something;
})(ReactEx = exports.ReactEx || (exports.ReactEx = {}));
var Seamless;
(function (Seamless) {
    var foo = { 0: 123, 2: 345 };
    console.log(foo[0]);
    foo[0] = 456;
})(Seamless = exports.Seamless || (exports.Seamless = {}));
var SeamlessArray;
(function (SeamlessArray) {
    var foo = [1, 2, 3];
    console.log(foo[0]);
    foo.push(4);
    foo = foo.concat([4]);
})(SeamlessArray = exports.SeamlessArray || (exports.SeamlessArray = {}));
var ClassGetter;
(function (ClassGetter) {
    var Person = (function () {
        function Person() {
            this.firstName = "John";
            this.lastName = "Doe";
        }
        Object.defineProperty(Person.prototype, "fullName", {
            get: function () {
                return this.firstName + this.lastName;
            },
            enumerable: true,
            configurable: true
        });
        return Person;
    }());
    var person = new Person();
    console.log(person.fullName);
    person.fullName = "Dear Reader";
})(ClassGetter = exports.ClassGetter || (exports.ClassGetter = {}));
var vsconst;
(function (vsconst) {
    var foo = 123;
    var bar;
})(vsconst || (vsconst = {}));
var aliasing;
(function (aliasing) {
    var foo = {
        bar: 123
    };
    function iMutateFoo(foo) {
        foo.bar = 456;
    }
    iMutateFoo(foo);
    console.log(foo.bar);
})(aliasing || (aliasing = {}));
var aliasing2;
(function (aliasing2) {
    var foo = {
        bar: 123
    };
    function iTakeFoo(foo) {
        foo.bar = 456;
    }
    iTakeFoo(foo);
})(aliasing2 || (aliasing2 = {}));


================================================
FILE: code/types/readonly.ts
================================================
export namespace Simple {
    function foo(config: {
        readonly bar: number,
        readonly bas: number
    }) {
        // ..
    }

    let config = { bar: 123, bas: 123 };
    foo(config);
    // You can be sure that `config` isn't changed 🌹
}

export namespace Type {
    type Foo = {
        readonly bar: number;
        readonly bas: number;
    }

    // Initialization is okay
    let foo: Foo = { bar: 123, bas: 456 };

    // Mutation is not
    foo.bar = 456; // Error: Left-hand side of assignment expression cannot be a constant or a read-only property
}


export namespace Class {
    class Foo {
        readonly bar = 1; // OK
        readonly baz: string;
        constructor() {
            this.baz = "hello";  // OK
        }
    }
}

export namespace ReactEx {
    declare namespace React {
        export class Component<P, U>{ }
    };

    interface Props {
        readonly foo: number;
    }
    interface State {
        readonly bar: number;
    }
    export class Something extends React.Component<Props, State>{
        // You can rest assured no one is going to do
        // this.props.foo = 123; (props are immutable)
        // this.state.bar = 456; (one should use this.setState)
    }
}

export namespace Seamless {
    /**
     * Declaration
     */
    interface Foo {
        readonly[x: number]: number;
    }

    /**
     * Usage
     */
    let foo: Foo = { 0: 123, 2: 345 };
    console.log(foo[0]);   // Okay (reading)
    foo[0] = 456;          // Error (mutating) : Readonly
}

export namespace SeamlessArray {
    let foo: ReadonlyArray<number> = [1, 2, 3];
    console.log(foo[0]);   // Okay
    foo.push(4);           // Error: `push` does not exist on ReadonlyArray as it mutates the array
    foo = foo.concat([4]); // Okay: create a copy
}


export namespace ClassGetter {
    class Person {
        firstName: string = "John";
        lastName: string = "Doe";
        get fullName() {
            return this.firstName + this.lastName;
        }
    }

    const person = new Person();
    console.log(person.fullName); // John Doe
    person.fullName = "Dear Reader"; // Error! fullName is readonly
}

namespace vsconst {
    const foo = 123;
    var bar: {
        readonly bar: number;
    }
}

namespace aliasing {
    let foo: {
        readonly bar: number;
    } = {
            bar: 123
        };

    function iMutateFoo(foo: { bar: number }) {
        foo.bar = 456;
    }

    iMutateFoo(foo); // The foo argument is aliased by the foo parameter
    console.log(foo.bar); // 456!
}

namespace aliasing2 {
    interface Foo {
        readonly bar: number;
    }
    let foo: Foo = {
        bar: 123
    };

    function iTakeFoo(foo: Foo) {
        foo.bar = 456; // Error!  bar is readonly
    }

    iTakeFoo(foo); // The foo argument is aliased by the foo parameter
}


================================================
FILE: code/types/stringLiteralType.js
================================================
"use strict";
var Simple;
(function (Simple) {
    var foo;
    foo = 'Bar';
})(Simple = exports.Simple || (exports.Simple = {}));
var Union;
(function (Union) {
    function move(distance, direction) {
    }
    move(1, "North");
    move(1, "Nurth");
})(Union = exports.Union || (exports.Union = {}));


================================================
FILE: code/types/tsconfig.json
================================================
{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "isolatedModules": false,
        "jsx": "react",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "declaration": false,
        "noImplicitAny": false,
        "removeComments": true,
        "noLib": false,
     
Download .txt
gitextract_d86sgzr5/

├── .gitattributes
├── .github/
│   └── workflows/
│       └── build.yml
├── .gitignore
├── CONTRIBUTING.md
├── GLOSSARY.md
├── LICENSE.md
├── README.md
├── SUMMARY.md
├── book.json
├── code/
│   ├── async-await/
│   │   ├── es5/
│   │   │   ├── asyncAwaitES5.js
│   │   │   ├── asyncAwaitES5.ts
│   │   │   └── tsconfig.json
│   │   └── es6/
│   │       ├── asyncAwaitES6.js
│   │       ├── asyncAwaitES6.ts
│   │       └── tsconfig.json
│   ├── compiler/
│   │   ├── package.json
│   │   ├── parser/
│   │   │   ├── runParser.js
│   │   │   └── runParser.ts
│   │   ├── scanner/
│   │   │   ├── runScanner.js
│   │   │   ├── runScanner.ts
│   │   │   ├── runScannerWithPositions.js
│   │   │   └── runScannerWithPositions.ts
│   │   ├── tsconfig.json
│   │   ├── tsd.json
│   │   └── typings/
│   │       ├── node/
│   │       │   └── node.d.ts
│   │       └── tsd.d.ts
│   ├── declarationspaces/
│   │   ├── declarationspace.js
│   │   └── declarationspace.ts
│   ├── dynamic-import-expressions/
│   │   ├── dynamicImportExpression.js
│   │   ├── dynamicImportExpression.ts
│   │   ├── package.json
│   │   └── tsconfig.json
│   ├── errors/
│   │   ├── common-errors.ts
│   │   ├── interpreting-errors.ts
│   │   └── tsconfig.json
│   ├── es6/
│   │   ├── classes/
│   │   │   ├── abstract.js
│   │   │   ├── abstract.ts
│   │   │   ├── class.js
│   │   │   ├── class.ts
│   │   │   ├── super.js
│   │   │   ├── super.ts
│   │   │   └── tsconfig.json
│   │   ├── const.js
│   │   ├── const.ts
│   │   ├── destructuring.js
│   │   ├── destructuring.ts
│   │   ├── enums.js
│   │   ├── enums.ts
│   │   ├── for..of.js
│   │   ├── for..of.ts
│   │   ├── forof.js
│   │   ├── iterators.js
│   │   ├── iterators.ts
│   │   ├── let.js
│   │   ├── let.ts
│   │   ├── rest-parameters.js
│   │   ├── rest-parameters.ts
│   │   ├── spread-operator.js
│   │   ├── spread-operator.ts
│   │   ├── template-strings.js
│   │   ├── template-strings.ts
│   │   ├── test.js
│   │   ├── test.ts
│   │   └── tsconfig.json
│   ├── javascript/
│   │   ├── closure.js
│   │   ├── closure.ts
│   │   └── tsconfig.json
│   ├── tips/
│   │   ├── bindIsBad.js
│   │   ├── bindIsBad.ts
│   │   ├── currying.js
│   │   ├── currying.ts
│   │   ├── lazyObjectLiteralInitialization.js
│   │   ├── lazyObjectLiteralInitialization.ts
│   │   ├── mixins.js
│   │   ├── mixins.ts
│   │   ├── nominalTyping.js
│   │   ├── nominalTyping.ts
│   │   ├── statefulFunctions.js
│   │   ├── statefulFunctions.ts
│   │   ├── stringEnums.js
│   │   ├── stringEnums.ts
│   │   └── tsconfig.json
│   └── types/
│       ├── assertion.js
│       ├── assertion.ts
│       ├── callable.ts
│       ├── freshness/
│       │   ├── freshness.js
│       │   ├── freshness.ts
│       │   ├── index-signatures.js
│       │   ├── index-signatures.ts
│       │   └── tsconfig.json
│       ├── functions.js
│       ├── functions.ts
│       ├── generics.js
│       ├── generics.ts
│       ├── interfaces.js
│       ├── interfaces.ts
│       ├── keyof.ts
│       ├── lib/
│       │   ├── exclude/
│       │   │   ├── nolibd.js
│       │   │   ├── nolibd.ts
│       │   │   └── tsconfig.json
│       │   └── usage/
│       │       ├── libd.js
│       │       ├── libd.ts
│       │       └── tsconfig.json
│       ├── libd.js
│       ├── literal-types.js
│       ├── literal-types.ts
│       ├── migrating/
│       │   ├── migrating.js
│       │   ├── migrating.ts
│       │   └── tsconfig.json
│       ├── readonly.js
│       ├── readonly.ts
│       ├── stringLiteralType.js
│       ├── tsconfig.json
│       ├── type-compatibility.js
│       ├── type-compatibility.ts
│       ├── type-inference.js
│       ├── type-inference.ts
│       ├── typeGuard.js
│       ├── typeGuard.ts
│       ├── types.js
│       └── types.ts
├── docs/
│   ├── arrow-functions.md
│   ├── async-await.md
│   ├── classes-emit.md
│   ├── classes.md
│   ├── compiler/
│   │   ├── ast-tip-children.md
│   │   ├── ast-tip-syntaxkind.md
│   │   ├── ast-trivia.md
│   │   ├── ast.md
│   │   ├── binder-container.md
│   │   ├── binder-declarations.md
│   │   ├── binder-diagnostics.md
│   │   ├── binder-functions.md
│   │   ├── binder-symbolflags.md
│   │   ├── binder-symboltable.md
│   │   ├── binder.md
│   │   ├── checker-diagnostics.md
│   │   ├── checker-global.md
│   │   ├── checker.md
│   │   ├── contributing.md
│   │   ├── emitter-functions.md
│   │   ├── emitter-sourcemaps.md
│   │   ├── emitter.md
│   │   ├── make-global.md
│   │   ├── overview.md
│   │   ├── parser-functions.md
│   │   ├── parser.md
│   │   ├── program.md
│   │   └── scanner.md
│   ├── compiler-options.md
│   ├── const.md
│   ├── declaration.md
│   ├── destructuring.md
│   ├── enums.md
│   ├── errors/
│   │   ├── common-errors.md
│   │   ├── interpreting-errors.md
│   │   └── main.md
│   ├── for...of.md
│   ├── future-javascript.md
│   ├── generators.md
│   ├── getting-started.md
│   ├── iterators.md
│   ├── javascript/
│   │   ├── closure.md
│   │   ├── equality.md
│   │   ├── null-undefined.md
│   │   ├── number.md
│   │   ├── recap.md
│   │   ├── references.md
│   │   ├── this.md
│   │   └── truthy.md
│   ├── jsx/
│   │   ├── others.md
│   │   ├── react.md
│   │   └── tsx.md
│   ├── let.md
│   ├── npm/
│   │   └── index.md
│   ├── options/
│   │   ├── intro.md
│   │   ├── noImplicitAny.md
│   │   └── strictNullChecks.md
│   ├── project/
│   │   ├── compilation-context.md
│   │   ├── declarationspaces.md
│   │   ├── dynamic-import-expressions.md
│   │   ├── external-modules.md
│   │   ├── files.md
│   │   ├── globals.md
│   │   ├── module-resolution.md
│   │   ├── modules.md
│   │   ├── namespaces.md
│   │   ├── project.md
│   │   └── tsconfig.md
│   ├── promise.md
│   ├── quick/
│   │   ├── browser.md
│   │   ├── library.md
│   │   └── nodejs.md
│   ├── rest-parameters.md
│   ├── spread-operator.md
│   ├── staging/
│   │   ├── async-await.md
│   │   └── generators.md
│   ├── state/
│   │   └── mobx.md
│   ├── styleguide/
│   │   ├── sample.js
│   │   ├── sample.ts
│   │   ├── styleguide.md
│   │   └── tsconfig.json
│   ├── template-strings.md
│   ├── testing/
│   │   ├── cypress.md
│   │   ├── intro.md
│   │   └── jest.md
│   ├── tips/
│   │   ├── barrel.md
│   │   ├── build-toggles.md
│   │   ├── classesAreUseful.md
│   │   ├── create-arrays.md
│   │   ├── currying.md
│   │   ├── defaultIsBad.md
│   │   ├── functionParameters.md
│   │   ├── jquery.md
│   │   ├── lazyObjectLiteralInitialization.md
│   │   ├── main.md
│   │   ├── nominalTyping.md
│   │   ├── outFile.md
│   │   ├── propertySetters.md
│   │   ├── singleton.md
│   │   ├── statefulFunctions.md
│   │   ├── staticConstructor.md
│   │   ├── stringEnums.md
│   │   ├── typeInstantiation.md
│   │   └── typed-event.md
│   ├── tools/
│   │   ├── changelog.md
│   │   ├── eslint.md
│   │   ├── husky.md
│   │   ├── intro.md
│   │   └── prettier.md
│   ├── types/
│   │   ├── @types.md
│   │   ├── advanced.md
│   │   ├── ambient/
│   │   │   ├── d.ts.md
│   │   │   ├── intro.md
│   │   │   └── variables.md
│   │   ├── callable.md
│   │   ├── discriminated-unions.md
│   │   ├── exceptions.md
│   │   ├── freshness.md
│   │   ├── functions.md
│   │   ├── generics.md
│   │   ├── index-signatures.md
│   │   ├── interfaces.md
│   │   ├── lib.d.ts.md
│   │   ├── literal-types.md
│   │   ├── migrating.md
│   │   ├── mixins.md
│   │   ├── moving-types.md
│   │   ├── never.md
│   │   ├── readonly.md
│   │   ├── type-assertion.md
│   │   ├── type-compatibility.md
│   │   ├── type-inference.md
│   │   ├── type-system.md
│   │   └── typeGuard.md
│   └── why-typescript.md
├── footer.md
├── header.html
├── images/
│   ├── promise states and fates.vsd
│   └── venn.vsd
└── snippets/
    └── md-snippets.cson
Download .txt
SYMBOL INDEX (397 symbols across 73 files)

FILE: code/async-await/es5/asyncAwaitES5.js
  function fulfilled (line 3) | function fulfilled(value) { try { step(generator.next(value)); } catch (...
  function rejected (line 4) | function rejected(value) { try { step(generator["throw"](value)); } catc...
  function step (line 5) | function step(result) { result.done ? resolve(result.value) : new P(func...
  function verb (line 12) | function verb(n) { return function (v) { return step([n, v]); }; }
  function step (line 13) | function step(op) {
  function delay (line 36) | function delay(milliseconds, count) {
  function dramaticWelcome (line 44) | function dramaticWelcome() {

FILE: code/async-await/es5/asyncAwaitES5.ts
  function delay (line 1) | function delay(milliseconds: number, count: number): Promise<number> {
  function dramaticWelcome (line 10) | async function dramaticWelcome(): Promise<void> {

FILE: code/async-await/es6/asyncAwaitES6.js
  function fulfilled (line 3) | function fulfilled(value) { try { step(generator.next(value)); } catch (...
  function rejected (line 4) | function rejected(value) { try { step(generator["throw"](value)); } catc...
  function step (line 5) | function step(result) { result.done ? resolve(result.value) : new P(func...
  function delay (line 9) | function delay(milliseconds, count) {
  function dramaticWelcome (line 17) | function dramaticWelcome() {

FILE: code/async-await/es6/asyncAwaitES6.ts
  function delay (line 1) | function delay(milliseconds: number, count: number): Promise<number> {
  function dramaticWelcome (line 10) | async function dramaticWelcome(): Promise<void> {

FILE: code/compiler/parser/runParser.js
  function printAllChildren (line 2) | function printAllChildren(node, depth) {

FILE: code/compiler/parser/runParser.ts
  function printAllChildren (line 3) | function printAllChildren(node: ts.Node, depth = 0) {

FILE: code/compiler/scanner/runScanner.js
  function initializeState (line 3) | function initializeState(text) {

FILE: code/compiler/scanner/runScanner.ts
  function initializeState (line 7) | function initializeState(text: string) {

FILE: code/compiler/scanner/runScannerWithPositions.js
  function initializeState (line 3) | function initializeState(text) {

FILE: code/compiler/scanner/runScannerWithPositions.ts
  function initializeState (line 7) | function initializeState(text: string) {

FILE: code/compiler/typings/node/node.d.ts
  type Buffer (line 63) | interface Buffer extends NodeBuffer {}
  type ErrnoException (line 142) | interface ErrnoException extends Error {
  type EventEmitter (line 150) | interface EventEmitter {
  type ReadableStream (line 161) | interface ReadableStream extends EventEmitter {
  type WritableStream (line 174) | interface WritableStream extends EventEmitter {
  type ReadWriteStream (line 185) | interface ReadWriteStream extends ReadableStream, WritableStream {}
  type Process (line 187) | interface Process extends EventEmitter {
  type Global (line 255) | interface Global {
  type Timer (line 320) | interface Timer {
  type NodeBuffer (line 329) | interface NodeBuffer {
  class EventEmitter (line 395) | class EventEmitter implements NodeJS.EventEmitter {
  type Server (line 414) | interface Server extends events.EventEmitter {
  type ServerRequest (line 426) | interface ServerRequest extends IncomingMessage {
  type ServerResponse (line 429) | interface ServerResponse extends events.EventEmitter, stream.Writable {
  type ClientRequest (line 455) | interface ClientRequest extends events.EventEmitter, stream.Writable {
  type IncomingMessage (line 476) | interface IncomingMessage extends events.EventEmitter, stream.Readable {
  type ClientResponse (line 504) | interface ClientResponse extends IncomingMessage { }
  type AgentOptions (line 506) | interface AgentOptions {
  class Agent (line 526) | class Agent {
  type ClusterSettings (line 559) | interface ClusterSettings {
  class Worker (line 565) | class Worker extends events.EventEmitter {
  type ZlibOptions (line 597) | interface ZlibOptions { chunkSize?: number; windowBits?: number; level?:...
  type Gzip (line 599) | interface Gzip extends stream.Transform { }
  type Gunzip (line 600) | interface Gunzip extends stream.Transform { }
  type Deflate (line 601) | interface Deflate extends stream.Transform { }
  type Inflate (line 602) | interface Inflate extends stream.Transform { }
  type DeflateRaw (line 603) | interface DeflateRaw extends stream.Transform { }
  type InflateRaw (line 604) | interface InflateRaw extends stream.Transform { }
  type Unzip (line 605) | interface Unzip extends stream.Transform { }
  type ServerOptions (line 685) | interface ServerOptions {
  type RequestOptions (line 700) | interface RequestOptions {
  type Agent (line 718) | interface Agent {
  type Server (line 726) | interface Server extends tls.Server { }
  type ucs2 (line 739) | interface ucs2 {
  type ReplOptions (line 750) | interface ReplOptions {
  type ReadLine (line 768) | interface ReadLine extends events.EventEmitter {
  type ReadLineOptions (line 777) | interface ReadLineOptions {
  type Context (line 787) | interface Context { }
  type Script (line 788) | interface Script {
  type ChildProcess (line 803) | interface ChildProcess extends events.EventEmitter {
  type Url (line 877) | interface Url {
  type UrlOptions (line 892) | interface UrlOptions {
  type Socket (line 928) | interface Socket extends stream.Duplex {
  type Server (line 971) | interface Server extends Socket {
  type RemoteInfo (line 996) | interface RemoteInfo {
  type AddressInfo (line 1002) | interface AddressInfo {
  type Socket (line 1010) | interface Socket extends events.EventEmitter {
  type Stats (line 1027) | interface Stats {
  type FSWatcher (line 1050) | interface FSWatcher extends events.EventEmitter {
  type ReadStream (line 1054) | interface ReadStream extends stream.Readable {
  type WriteStream (line 1057) | interface WriteStream extends stream.Writable {
  type ParsedPath (line 1310) | interface ParsedPath {
  type NodeStringDecoder (line 1452) | interface NodeStringDecoder {
  type TlsOptions (line 1469) | interface TlsOptions {
  type ConnectionOptions (line 1484) | interface ConnectionOptions {
  type Server (line 1498) | interface Server extends net.Server {
  type ClearTextStream (line 1516) | interface ClearTextStream extends stream.Duplex {
  type SecurePair (line 1533) | interface SecurePair {
  type SecureContextOptions (line 1538) | interface SecureContextOptions {
  type SecureContext (line 1549) | interface SecureContext {
  type CredentialDetails (line 1562) | interface CredentialDetails {
  type Credentials (line 1571) | interface Credentials { context?: any; }
  type Hash (line 1576) | interface Hash {
  type Hmac (line 1582) | interface Hmac {
  type Cipher (line 1590) | interface Cipher {
  type Decipher (line 1599) | interface Decipher {
  type Signer (line 1607) | interface Signer {
  type Verify (line 1612) | interface Verify {
  type DiffieHellman (line 1618) | interface DiffieHellman {
  type Stream (line 1640) | interface Stream extends events.EventEmitter {
  type ReadableOptions (line 1644) | interface ReadableOptions {
  class Readable (line 1650) | class Readable extends events.EventEmitter implements NodeJS.ReadableStr...
  type WritableOptions (line 1666) | interface WritableOptions {
  class Writable (line 1671) | class Writable extends events.EventEmitter implements NodeJS.WritableStr...
  type DuplexOptions (line 1685) | interface DuplexOptions extends ReadableOptions, WritableOptions {
  class Duplex (line 1690) | class Duplex extends Readable implements NodeJS.ReadWriteStream {
  type TransformOptions (line 1704) | interface TransformOptions extends ReadableOptions, WritableOptions {}
  class Transform (line 1707) | class Transform extends events.EventEmitter implements NodeJS.ReadWriteS...
  class PassThrough (line 1733) | class PassThrough extends Transform {}
  type InspectOptions (line 1737) | interface InspectOptions {
  class AssertionError (line 1762) | class AssertionError implements Error {
  type ReadStream (line 1806) | interface ReadStream extends net.Socket {
  type WriteStream (line 1810) | interface WriteStream extends net.Socket {
  class Domain (line 1819) | class Domain extends events.EventEmitter {

FILE: code/declarationspaces/declarationspace.js
  function Foo (line 4) | function Foo() {
  function Foo (line 20) | function Foo() {
  function log (line 38) | function log(msg) {
  function error (line 42) | function error(msg) {
  function Foo (line 52) | function Foo() {
  function Foo (line 62) | function Foo() {

FILE: code/declarationspaces/declarationspace.ts
  class Foo (line 2) | class Foo { }
  type Bar (line 3) | interface Bar { }
  type Bas (line 4) | type Bas = {}
  type Bar (line 12) | interface Bar { }
  class Foo (line 17) | class Foo { }
  function log (line 36) | function log(msg) {
  function error (line 39) | function error(msg) {
  class Foo (line 50) | class Foo { }
  class Foo (line 56) | class Foo { }

FILE: code/dynamic-import-expressions/dynamicImportExpression.js
  function myApp (line 2) | function myApp() {

FILE: code/dynamic-import-expressions/dynamicImportExpression.ts
  function myApp (line 2) | function myApp() {

FILE: code/errors/interpreting-errors.ts
  type SomethingComplex (line 3) | type SomethingComplex = {
  function takeSomethingComplex (line 7) | function takeSomethingComplex(arg: SomethingComplex) {
  function getBar (line 9) | function getBar(): string {

FILE: code/es6/classes/abstract.js
  function Restable (line 3) | function Restable() {

FILE: code/es6/classes/abstract.ts
  class Restable (line 3) | class Restable {

FILE: code/es6/classes/class.js
  function __ (line 3) | function __() { this.constructor = d; }
  function Point (line 8) | function Point(x, y) {
  function Point3D (line 22) | function Point3D(x, y, z) {
  function Something (line 33) | function Something() {

FILE: code/es6/classes/class.ts
  class Point (line 1) | class Point {
    method constructor (line 4) | constructor(x: number, y: number) {
    method add (line 8) | add(point: Point) {
  class Point3D (line 17) | class Point3D extends Point {
    method constructor (line 19) | constructor(x: number, y: number, z: number) {
    method add (line 23) | add(point: Point3D) {
  class Something (line 29) | class Something {
    method constructor (line 31) | constructor() {

FILE: code/es6/classes/super.js
  function __ (line 3) | function __() { this.constructor = d; }
  function Base (line 10) | function Base() {
  function Child (line 17) | function Child() {
  function Base (line 28) | function Base() {
  function Child (line 35) | function Child() {
  function Base (line 46) | function Base() {
  function Child (line 53) | function Child() {

FILE: code/es6/classes/super.ts
  class Base (line 4) | class Base {
    method log (line 5) | log() { console.log('hello world'); }
  class Child (line 8) | class Child extends Base {
    method logWorld (line 9) | logWorld() { super.log() }
    method logWorld (line 19) | logWorld() { this.log() }
    method logWorld (line 29) | logWorld() { super.log() }
  class Base (line 14) | class Base {
    method log (line 5) | log() { console.log('hello world'); }
  class Child (line 18) | class Child extends Base {
    method logWorld (line 9) | logWorld() { super.log() }
    method logWorld (line 19) | logWorld() { this.log() }
    method logWorld (line 29) | logWorld() { super.log() }
  class Base (line 24) | class Base {
    method log (line 5) | log() { console.log('hello world'); }
  class Child (line 28) | class Child extends Base {
    method logWorld (line 9) | logWorld() { super.log() }
    method logWorld (line 19) | logWorld() { this.log() }
    method logWorld (line 29) | logWorld() { super.log() }

FILE: code/es6/enums.js
  function printAnimalAbilities (line 30) | function printAnimalAbilities(animal) {
  function isBusinessDay (line 64) | function isBusinessDay(day) {

FILE: code/es6/enums.ts
  type Color (line 3) | enum Color {
  type Color (line 9) | enum Color {
  type Tristate (line 19) | enum Tristate {
  type AnimalFlags (line 35) | enum AnimalFlags {
  function printAnimalAbilities (line 41) | function printAnimalAbilities(animal) {
  type Weekday (line 65) | enum Weekday {
  function isBusinessDay (line 75) | function isBusinessDay(day: Weekday) {

FILE: code/es6/iterators.js
  function Component (line 2) | function Component(name) {
  function Frame (line 8) | function Frame(name, components) {

FILE: code/es6/iterators.ts
  class Component (line 7) | class Component {
    method constructor (line 8) | constructor (public name: string) {}
  class Frame (line 11) | class Frame {
    method constructor (line 15) | constructor(public name: string, public components: Component[]) {}
    method next (line 17) | public next(): {done: boolean, value?: Component} {

FILE: code/es6/let.js
  function test (line 21) | function test() {

FILE: code/es6/let.ts
  function test (line 19) | function test() {

FILE: code/es6/rest-parameters.js
  function iTakeItAll (line 3) | function iTakeItAll(first, second) {

FILE: code/es6/rest-parameters.ts
  function iTakeItAll (line 2) | function iTakeItAll(first, second, ...allOthers) {

FILE: code/es6/template-strings.js
  function htmlEscape (line 31) | function htmlEscape(literals) {

FILE: code/es6/template-strings.ts
  function htmlEscape (line 34) | function htmlEscape(literals, ...placeholders) {

FILE: code/javascript/closure.js
  function outerFunction (line 2) | function outerFunction(arg) {
  function outerFunction (line 12) | function outerFunction(arg) {
  function createCounter (line 23) | function createCounter() {

FILE: code/javascript/closure.ts
  function outerFunction (line 1) | function outerFunction(arg) {
  function outerFunction (line 16) | function outerFunction(arg) {
  function createCounter (line 31) | function createCounter() {

FILE: code/tips/bindIsBad.js
  function Adder (line 3) | function Adder(a) {
  function useAdd (line 11) | function useAdd(add) {
  function twoParams (line 17) | function twoParams(a, b) {
  function twoParams (line 25) | function twoParams(a, b) {

FILE: code/tips/bindIsBad.ts
  class Adder (line 3) | class Adder {
    method constructor (line 4) | constructor(public a: string) { }
    method add (line 6) | add(b: string): string {
  function useAdd (line 11) | function useAdd(add: (x: number) => number) {
  function twoParams (line 20) | function twoParams(a: number, b: number) {
  function twoParams (line 28) | function twoParams(a: number, b: number) {

FILE: code/tips/lazyObjectLiteralInitialization.ts
  type Foo (line 21) | interface Foo {

FILE: code/tips/mixins.js
  function __ (line 3) | function __() { this.constructor = d; }
  function Disposable (line 7) | function Disposable() {
  function Activatable (line 15) | function Activatable() {
  function SmartObject (line 32) | function SmartObject() {
  function applyMixins (line 45) | function applyMixins(derivedCtor, baseCtors) {

FILE: code/tips/mixins.ts
  class Disposable (line 2) | class Disposable {
    method dispose (line 4) | dispose() {
  class Activatable (line 11) | class Activatable {
    method activate (line 13) | activate() {
    method deactivate (line 16) | deactivate() {
  type ActivatibleDisposible (line 21) | interface ActivatibleDisposible extends Disposable, Activatable {
  class SmartObject (line 31) | class SmartObject extends ActivatibleDisposible {
    method constructor (line 32) | constructor() {
    method interact (line 37) | interact() {
  function applyMixins (line 50) | function applyMixins(derivedCtor: any, baseCtors: any[]) {

FILE: code/tips/nominalTyping.ts
  type Id (line 3) | type Id<T extends string> = {
  type FooId (line 9) | type FooId = Id<'foo'>;
  type BarId (line 10) | type BarId = Id<'bar'>;
  type FooIdBrand (line 25) | enum FooIdBrand { }
  type FooId (line 26) | type FooId = FooIdBrand & string;
  type BarIdBrand (line 29) | enum BarIdBrand { }
  type BarId (line 30) | type BarId = BarIdBrand & string;
  type FooId (line 55) | interface FooId extends String {
  type BarId (line 60) | interface BarId extends String {

FILE: code/tips/statefulFunctions.js
  function class_1 (line 2) | function class_1() {

FILE: code/tips/stringEnums.ts
  type TriState (line 27) | type TriState = 'False' | 'True' | 'Unknown';

FILE: code/types/assertion.js
  function handler1 (line 21) | function handler1(event) {
  function handler2 (line 24) | function handler2(event) {
  function handler (line 27) | function handler(event) {

FILE: code/types/assertion.ts
  type Foo (line 10) | interface Foo {
  function handler1 (line 27) | function handler1(event: Event) {
  function handler2 (line 31) | function handler2(event: Event) {
  function handler (line 35) | function handler(event: Event) {

FILE: code/types/callable.ts
  type ReturnString (line 5) | interface ReturnString {
  type Complex (line 13) | interface Complex {
  type Overloaded (line 17) | interface Overloaded {
  type CallMeWithNewToGetString (line 39) | interface CallMeWithNewToGetString {

FILE: code/types/freshness/freshness.js
  function logName (line 4) | function logName(something) {
  function logName (line 16) | function logName(something) {
  function logIfHasName (line 24) | function logIfHasName(something) {

FILE: code/types/freshness/freshness.ts
  function logName (line 4) | function logName(something: { name: string }) {
  function logName (line 18) | function logName(something: { name: string }) {
  function logIfHasName (line 27) | function logIfHasName(something: { name?: string }) {
  type State (line 47) | interface State {
  class MyComponent (line 52) | class MyComponent {
    method setState (line 55) | setState(state: State) {
    method doSomething (line 59) | doSomething() {
    method setState (line 79) | setState(state: State) {
    method doSomething (line 83) | doSomething() {
  type State (line 71) | interface State {
  class MyComponent (line 76) | class MyComponent {
    method setState (line 55) | setState(state: State) {
    method doSomething (line 59) | doSomething() {
    method setState (line 79) | setState(state: State) {
    method doSomething (line 83) | doSomething() {

FILE: code/types/freshness/index-signatures.js
  function Foo (line 10) | function Foo(message) {

FILE: code/types/freshness/index-signatures.ts
  class Foo (line 7) | class Foo {
    method constructor (line 8) | constructor(public message: string) { }
    method log (line 9) | log() {
  method toString (line 20) | toString() {
  method toString (line 39) | toString() {
  type Foo (line 92) | interface Foo {
    method constructor (line 8) | constructor(public message: string) { }
    method log (line 9) | log() {
  type Bar (line 98) | interface Bar {
  type Foo (line 106) | interface Foo {
    method constructor (line 8) | constructor(public message: string) { }
    method log (line 9) | log() {
  type ArrStr (line 117) | interface ArrStr {
  type NestedCSS (line 128) | interface NestedCSS {
  type NestedCSS (line 146) | interface NestedCSS {

FILE: code/types/functions.js
  function foo (line 5) | function foo(sampleParameter) { }
  function foo (line 9) | function foo(sample) {
  function foo (line 15) | function foo(sample) {
  function foo (line 21) | function foo() {
  function foo (line 28) | function foo(bar, bas) {
  function foo (line 35) | function foo(bar, bas) {
  function padding (line 44) | function padding(a, b, c, d) {
  function padding (line 63) | function padding(a, b, c, d) {

FILE: code/types/functions.ts
  function foo (line 9) | function foo(sampleParameter: { bar: number }) { }
  type Foo (line 13) | interface Foo {
  function foo (line 18) | function foo(sample: Foo) {
  type Foo (line 24) | interface Foo {
  function foo (line 28) | function foo(sample: Foo) {
  function foo (line 34) | function foo() {
  function foo (line 42) | function foo(bar: number, bas?: string): void {
  function foo (line 51) | function foo(bar: number, bas: string = 'world') {
  function padding (line 60) | function padding(a: number, b?: number, c?: number, d?: any) {
  function padding (line 81) | function padding(a: number, b?: number, c?: number, d?: number) {

FILE: code/types/generics.js
  function Queue (line 4) | function Queue() {
  function QueueNumber (line 21) | function QueueNumber() {
  function Queue (line 36) | function Queue() {

FILE: code/types/generics.ts
  class Queue (line 2) | class Queue {
  class QueueNumber (line 18) | class QueueNumber {
  class Queue (line 33) | class Queue<T> {
  type LoadUsersResponse (line 62) | type LoadUsersResponse = {
  function loadUsers (line 68) | function loadUsers() {

FILE: code/types/interfaces.js
  function MyPoint (line 4) | function MyPoint() {
  function MyPoint (line 12) | function MyPoint() {

FILE: code/types/interfaces.ts
  type Point (line 2) | interface Point {
  class MyPoint (line 6) | class MyPoint implements Point {
  type Point (line 12) | interface Point {
  class MyPoint (line 17) | class MyPoint implements Point { // ERROR : missing member `z`

FILE: code/types/keyof.ts
  type Colors (line 6) | type Colors = keyof typeof colors;

FILE: code/types/lib/usage/libd.ts
  type Window (line 6) | interface Window {
  type Math (line 18) | interface Math {
  type Date (line 25) | interface Date {
  type String (line 29) | interface String {

FILE: code/types/literal-types.js
  function move (line 9) | function move(distance, direction) {

FILE: code/types/literal-types.ts
  type CardinalDirection (line 8) | type CardinalDirection =
  function move (line 14) | function move(distance: number, direction: CardinalDirection) {
  function strEnum (line 25) | function strEnum<T extends string>(o: Array<T>): {[K in T]: K} {
  type Direction (line 44) | type Direction = keyof typeof Direction;

FILE: code/types/migrating/migrating.ts
  type JQuery (line 2) | type JQuery = any;

FILE: code/types/readonly.js
  function __ (line 4) | function __() { this.constructor = d; }
  function foo (line 9) | function foo(config) {
  function Foo (line 22) | function Foo() {
  function Something (line 34) | function Something() {
  function Person (line 57) | function Person() {
  function iMutateFoo (line 84) | function iMutateFoo(foo) {
  function iTakeFoo (line 95) | function iTakeFoo(foo) {

FILE: code/types/readonly.ts
  function foo (line 2) | function foo(config: {
  type Foo (line 15) | type Foo = {
    method constructor (line 32) | constructor() {
  class Foo (line 29) | class Foo {
    method constructor (line 32) | constructor() {
  class Component (line 40) | class Component<P, U>{ }
  type Props (line 43) | interface Props {
  type State (line 46) | interface State {
  class Something (line 49) | class Something extends React.Component<Props, State>{
  type Foo (line 60) | interface Foo {
    method constructor (line 32) | constructor() {
  class Person (line 81) | class Person {
    method fullName (line 84) | get fullName() {
  function iMutateFoo (line 108) | function iMutateFoo(foo: { bar: number }) {
  type Foo (line 117) | interface Foo {
    method constructor (line 32) | constructor() {
  function iTakeFoo (line 124) | function iTakeFoo(foo: Foo) {

FILE: code/types/stringLiteralType.js
  function move (line 9) | function move(distance, direction) {

FILE: code/types/type-compatibility.js
  function __ (line 4) | function __() { this.constructor = d; }
  function Animal (line 52) | function Animal() {
  function Cat (line 58) | function Cat() {
  function Size (line 68) | function Size() {
  function Animal (line 79) | function Animal(name) {
  function Cat (line 86) | function Cat() {

FILE: code/types/type-compatibility.ts
  type Point2D (line 23) | interface Point2D { x: number; y: number; }
  type Point3D (line 24) | interface Point3D { x: number; y: number; z: number; }
  type Point2D (line 46) | interface Point2D { x: number; y: number; }
  type Point3D (line 47) | interface Point3D { x: number; y: number; z: number; }
  class Animal (line 59) | class Animal { protected feet: number; }
    method constructor (line 80) | constructor(public name: string){}
  class Cat (line 60) | class Cat extends Animal { }
    method meow (line 81) | meow() { }
  class Size (line 69) | class Size { protected feet: number; }
  class Animal (line 80) | class Animal { constructor(public name: string){} }
    method constructor (line 80) | constructor(public name: string){}
  class Cat (line 81) | class Cat extends Animal { meow() { } }
    method meow (line 81) | meow() { }

FILE: code/types/type-inference.js
  function add (line 9) | function add(a, b) {
  function iTakeAnAdder (line 26) | function iTakeAnAdder(adder) {
  function iTakeAnAdder (line 63) | function iTakeAnAdder(adder) {
  function foo (line 81) | function foo(a, b) {
  function addOne (line 84) | function addOne(a) {

FILE: code/types/type-inference.ts
  function add (line 9) | function add(a: number, b: number) {
  type Adder (line 15) | type Adder = (a: number, b: number) => number;
  type Adder (line 20) | type Adder = (a: number, b: number) => number;
  type Adder (line 28) | type Adder = (a: number, b: number) => number;
  function iTakeAnAdder (line 29) | function iTakeAnAdder(adder: Adder) {
  type Adder (line 72) | type Adder = (numbers: { a: number, b: number }) => number;
  function iTakeAnAdder (line 73) | function iTakeAnAdder(adder: Adder) {
  type TwoNumberFunction (line 89) | type TwoNumberFunction = (a: number, b: number) => void;
  function foo (line 94) | function foo(a: number, b: number) {
  function addOne (line 97) | function addOne(a) {

FILE: code/types/typeGuard.js
  function doSomething (line 4) | function doSomething(x) {
  function Foo (line 15) | function Foo() {
  function Bar (line 22) | function Bar() {
  function doStuff (line 28) | function doStuff(arg) {
  function Foo (line 47) | function Foo() {
  function Bar (line 53) | function Bar() {
  function doStuff (line 58) | function doStuff(arg) {
  function isFoo (line 73) | function isFoo(arg) {
  function doStuff (line 76) | function doStuff(arg) {

FILE: code/types/typeGuard.ts
  function doSomething (line 2) | function doSomething(x: number | string) {
  class Foo (line 12) | class Foo {
  class Bar (line 17) | class Bar {
  function doStuff (line 22) | function doStuff(arg: Foo | Bar) {
  class Foo (line 42) | class Foo {
  class Bar (line 46) | class Bar {
  function doStuff (line 50) | function doStuff(arg: Foo | Bar) {
  type Foo (line 70) | interface Foo {
  type Bar (line 75) | interface Bar {
  function isFoo (line 83) | function isFoo(arg: any): arg is Foo {
  function doStuff (line 90) | function doStuff(arg: Foo | Bar) {

FILE: code/types/types.js
  function identity (line 4) | function identity(num) {
  function log (line 93) | function log(message) {
  function reverse (line 99) | function reverse(items) {
  function formatCommandline (line 144) | function formatCommandline(command) {
  function getOrSet (line 170) | function getOrSet(value) {
  function getOrSet (line 184) | function getOrSet(value) {
  function callMe (line 197) | function callMe(v1, v2) {

FILE: code/types/types.ts
  function identity (line 3) | function identity(num: number): number {
  type Name (line 40) | interface Name {
  function log (line 106) | function log(message): void {
  function reverse (line 112) | function reverse<T>(items: T[]): T[] {
  function formatCommandline (line 146) | function formatCommandline(command: string[]|string) {
  function getOrSet (line 173) | function getOrSet(value) {
  function getOrSet (line 190) | function getOrSet(value?: number) {
  function callMe (line 208) | function callMe(v1?: any, v2?: any): any {
  type StrOrNum (line 223) | type StrOrNum = string|number;

FILE: docs/styleguide/sample.js
  function BarFunc (line 5) | function BarFunc() { }
  function Foo (line 10) | function Foo() {

FILE: docs/styleguide/sample.ts
  function BarFunc (line 5) | function BarFunc() { }
  class Foo (line 9) | class Foo {
    method baz (line 11) | baz() { }
Condensed preview — 261 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (679K chars).
[
  {
    "path": ".gitattributes",
    "chars": 63,
    "preview": "# core.autocrlf\n* text=auto\n\n*.js linguist-language=TypeScript\n"
  },
  {
    "path": ".github/workflows/build.yml",
    "chars": 1371,
    "preview": "name: build ebook\n\non:\n  push:\n    branches:\n      - master\n  pull_request:\n    branches:\n      - master\n\njobs:\n  build:"
  },
  {
    "path": ".gitignore",
    "chars": 394,
    "preview": "# Mac \n*.DS_Store\n\n# IDEs\n.alm\n.vscode\n\n\n# Node rules:\n## Grunt intermediate storage (http://gruntjs.com/creating-plugin"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 1028,
    "preview": "# Contributing\n\nThis book is developed using [GitBook](https://github.com/GitbookIO/gitbook). Authored in Markdown files"
  },
  {
    "path": "GLOSSARY.md",
    "chars": 433,
    "preview": "# 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 str"
  },
  {
    "path": "LICENSE.md",
    "chars": 64,
    "preview": "Creative Commons \n\nhttps://creativecommons.org/licenses/by/4.0/\n"
  },
  {
    "path": "README.md",
    "chars": 6131,
    "preview": "[![YouTube Channel Subscribers](https://img.shields.io/youtube/channel/subscribers/UCGD_0i6L48hucTiiyhb5QzQ?style=social"
  },
  {
    "path": "SUMMARY.md",
    "chars": 5761,
    "preview": "# Summary\n\n* [Getting Started](docs/getting-started.md)\n  * [Why TypeScript](docs/why-typescript.md)\n* [JavaScript](docs"
  },
  {
    "path": "book.json",
    "chars": 688,
    "preview": "{\n  \"language\": \"en\",\n  \"author\": \"Basarat Ali Syed\",\n  \"title\": \"TypeScript Deep Dive\",\n  \"plugins\": [\"edit-link\", \"git"
  },
  {
    "path": "code/async-await/es5/asyncAwaitES5.js",
    "chars": 3415,
    "preview": "var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n    return new (P || (P = Pro"
  },
  {
    "path": "code/async-await/es5/asyncAwaitES5.ts",
    "chars": 569,
    "preview": "function delay(milliseconds: number, count: number): Promise<number> {\n    return new Promise<number>(resolve => {\n     "
  },
  {
    "path": "code/async-await/es5/tsconfig.json",
    "chars": 472,
    "preview": "{\n  \"compilerOptions\": {\n    \"target\": \"es5\",                          /* Specify ECMAScript target version: 'ES3' (defa"
  },
  {
    "path": "code/async-await/es6/asyncAwaitES6.js",
    "chars": 1175,
    "preview": "var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n    return new (P || (P = Pro"
  },
  {
    "path": "code/async-await/es6/asyncAwaitES6.ts",
    "chars": 569,
    "preview": "function delay(milliseconds: number, count: number): Promise<number> {\n    return new Promise<number>(resolve => {\n     "
  },
  {
    "path": "code/async-await/es6/tsconfig.json",
    "chars": 362,
    "preview": "{\n  \"compilerOptions\": {\n    \"target\": \"es6\",                          /* Specify ECMAScript target version: 'ES3' (defa"
  },
  {
    "path": "code/compiler/package.json",
    "chars": 297,
    "preview": "{\n  \"name\": \"compiler\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"runScanner.js\",\n  \"dependencies\": {\n    \"n"
  },
  {
    "path": "code/compiler/parser/runParser.js",
    "chars": 464,
    "preview": "var ts = require(\"ntypescript\");\nfunction printAllChildren(node, depth) {\n    if (depth === void 0) { depth = 0; }\n    c"
  },
  {
    "path": "code/compiler/parser/runParser.ts",
    "chars": 435,
    "preview": "import * as ts from \"ntypescript\";\n\nfunction printAllChildren(node: ts.Node, depth = 0) {\n    console.log(new Array(dept"
  },
  {
    "path": "code/compiler/scanner/runScanner.js",
    "chars": 465,
    "preview": "var ts = require(\"ntypescript\");\nvar scanner = ts.createScanner(2, true);\nfunction initializeState(text) {\n    scanner.s"
  },
  {
    "path": "code/compiler/scanner/runScanner.ts",
    "chars": 755,
    "preview": "import * as ts from \"ntypescript\";\n\n// TypeScript has a singelton scanner\nconst scanner = ts.createScanner(ts.ScriptTarg"
  },
  {
    "path": "code/compiler/scanner/runScannerWithPositions.js",
    "chars": 610,
    "preview": "var ts = require(\"ntypescript\");\nvar scanner = ts.createScanner(2, true);\nfunction initializeState(text) {\n    scanner.s"
  },
  {
    "path": "code/compiler/scanner/runScannerWithPositions.ts",
    "chars": 900,
    "preview": "import * as ts from \"ntypescript\";\n\n// TypeScript has a singelton scanner\nconst scanner = ts.createScanner(ts.ScriptTarg"
  },
  {
    "path": "code/compiler/tsconfig.json",
    "chars": 760,
    "preview": "{\n    \"version\": \"1.5.0-beta\",\n    \"compilerOptions\": {\n        \"target\": \"es5\",\n        \"module\": \"commonjs\",\n        \""
  },
  {
    "path": "code/compiler/tsd.json",
    "chars": 246,
    "preview": "{\n  \"version\": \"v4\",\n  \"repo\": \"borisyankov/DefinitelyTyped\",\n  \"ref\": \"master\",\n  \"path\": \"typings\",\n  \"bundle\": \"typin"
  },
  {
    "path": "code/compiler/typings/node/node.d.ts",
    "chars": 86373,
    "preview": "// Type definitions for Node.js v0.12.0\n// Project: http://nodejs.org/\n// Definitions by: Microsoft TypeScript <http://t"
  },
  {
    "path": "code/compiler/typings/tsd.d.ts",
    "chars": 40,
    "preview": "/// <reference path=\"node/node.d.ts\" />\n"
  },
  {
    "path": "code/declarationspaces/declarationspace.js",
    "chars": 1543,
    "preview": "var first;\n(function (first) {\n    var Foo = (function () {\n        function Foo() {\n        }\n        return Foo;\n    }"
  },
  {
    "path": "code/declarationspaces/declarationspace.ts",
    "chars": 1218,
    "preview": "export module first {\n    class Foo { }\n    interface Bar { }\n    type Bas = {}\n\n    var foo: Foo;\n    var bar: Bar;\n   "
  },
  {
    "path": "code/dynamic-import-expressions/dynamicImportExpression.js",
    "chars": 487,
    "preview": "\"use strict\";\nfunction myApp() {\n    import(/* webpackChunkName: \"momentjs\" */ \"moment\")\n        .then(function (moment)"
  },
  {
    "path": "code/dynamic-import-expressions/dynamicImportExpression.ts",
    "chars": 496,
    "preview": "\nfunction myApp() {\n    import(/* webpackChunkName: \"momentjs\" */ \"moment\")\n        .then((moment) => {\n            // l"
  },
  {
    "path": "code/dynamic-import-expressions/package.json",
    "chars": 392,
    "preview": "{\n  \"name\": \"dynamic-import-expressions\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"dynamicImportExpression."
  },
  {
    "path": "code/dynamic-import-expressions/tsconfig.json",
    "chars": 450,
    "preview": "{\n    \"compilerOptions\": {\n        \"target\": \"es5\",                          \n        \"module\": \"esnext\",               "
  },
  {
    "path": "code/errors/common-errors.ts",
    "chars": 44,
    "preview": "ga();\n\nimport {debounce} from \"underscore\";\n"
  },
  {
    "path": "code/errors/interpreting-errors.ts",
    "chars": 391,
    "preview": "export const module = 123;\n\ntype SomethingComplex = {\n  foo: number,\n  bar: string\n}\nfunction takeSomethingComplex(arg: "
  },
  {
    "path": "code/errors/tsconfig.json",
    "chars": 50,
    "preview": "{\n  \"compilerOptions\": {\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "code/es6/classes/abstract.js",
    "chars": 142,
    "preview": "exports.foo = 123;\nvar Restable = (function () {\n    function Restable() {\n        this.abstract = toJSON();\n    }\n    r"
  },
  {
    "path": "code/es6/classes/abstract.ts",
    "chars": 72,
    "preview": "export var foo = 123;\n\nclass Restable {\n    abstract toJSON() : any;\n}\n\n"
  },
  {
    "path": "code/es6/classes/class.js",
    "chars": 1143,
    "preview": "var __extends = this.__extends || function (d, b) {\n    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n    funct"
  },
  {
    "path": "code/es6/classes/class.ts",
    "chars": 798,
    "preview": "class Point {\n    x: number;\n    y: number;\n    constructor(x: number, y: number) {\n        this.x = x;\n        this.y ="
  },
  {
    "path": "code/es6/classes/super.js",
    "chars": 1757,
    "preview": "var __extends = (this && this.__extends) || function (d, b) {\n    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];"
  },
  {
    "path": "code/es6/classes/super.ts",
    "chars": 600,
    "preview": "export var foo = 123;\n\nmodule asdf {\n    class Base {\n        log() { console.log('hello world'); }\n    }\n\n    class Chi"
  },
  {
    "path": "code/es6/classes/tsconfig.json",
    "chars": 402,
    "preview": "{\n    \"version\": \"1.4.1\",\n    \"compilerOptions\": {\n        \"target\": \"es5\",\n        \"module\": \"commonjs\",\n        \"decla"
  },
  {
    "path": "code/es6/const.js",
    "chars": 692,
    "preview": "exports.asdfasdfasfadf = 123;\nvar mustbeinit;\n(function (mustbeinit) {\n    var foo;\n})(mustbeinit || (mustbeinit = {}));"
  },
  {
    "path": "code/es6/const.ts",
    "chars": 551,
    "preview": "export var asdfasdfasfadf = 123;\n\n\nnamespace mustbeinit {\n    const foo;\n}\n\nnamespace cantbechanged {\n    const foo = 12"
  },
  {
    "path": "code/es6/destructuring.js",
    "chars": 813,
    "preview": "exports.destructuring = true;\nvar m1;\n(function (m1) {\n    var x = 1, y = 2;\n    _a = [\n        y,\n        x\n    ], x = "
  },
  {
    "path": "code/es6/destructuring.ts",
    "chars": 493,
    "preview": "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"
  },
  {
    "path": "code/es6/enums.js",
    "chars": 2647,
    "preview": "\"use strict\";\nexports.foo = 123;\nvar Color;\n(function (Color) {\n    Color[Color[\"Red\"] = 0] = \"Red\";\n    Color[Color[\"Gr"
  },
  {
    "path": "code/es6/enums.ts",
    "chars": 1913,
    "preview": "export const foo = 123;\n\nenum Color {\n    Red,\n    Green,\n    Blue\n}\n\nenum Color {\n    DarkRed = 3,\n    DarkGreen,\n    D"
  },
  {
    "path": "code/es6/for..of.js",
    "chars": 897,
    "preview": "exports.forof = true;\nvar m0;\n(function (m0) {\n    var someArray = [\n        9,\n        2,\n        5\n    ];\n    for (var"
  },
  {
    "path": "code/es6/for..of.ts",
    "chars": 649,
    "preview": "export var forof = true;\n\nmodule m0 {\n    var someArray = [9, 2, 5];\n    for (var item in someArray) {\n        console.l"
  },
  {
    "path": "code/es6/forof.js",
    "chars": 897,
    "preview": "exports.forof = true;\nvar m0;\n(function (m0) {\n    var someArray = [\n        9,\n        2,\n        5\n    ];\n    for (var"
  },
  {
    "path": "code/es6/iterators.js",
    "chars": 961,
    "preview": "var Component = (function () {\n    function Component(name) {\n        this.name = name;\n    }\n    return Component;\n}())"
  },
  {
    "path": "code/es6/iterators.ts",
    "chars": 1358,
    "preview": "// The book's chapter describes usage of Iterators with ES6 target\n// This example showing usage of iterators with ES5 t"
  },
  {
    "path": "code/es6/let.js",
    "chars": 1828,
    "preview": "exports.asdfasdfasfadf = 123;\nvar first;\n(function (first) {\n    var something = [\n        1,\n        2,\n        3\n    ]"
  },
  {
    "path": "code/es6/let.ts",
    "chars": 1562,
    "preview": "export var asdfasdfasfadf = 123;\n\nmodule first {\n    let something = [1, 2, 3];\n\n\n}\n\nmodule second {\n    var foo = 123;\n"
  },
  {
    "path": "code/es6/rest-parameters.js",
    "chars": 371,
    "preview": "var rest;\n(function (rest) {\n    function iTakeItAll(first, second) {\n        var allOthers = [];\n        for (var _i = "
  },
  {
    "path": "code/es6/rest-parameters.ts",
    "chars": 216,
    "preview": "export module rest {\n    function iTakeItAll(first, second, ...allOthers) {\n        console.log(allOthers);\n    }\n    iT"
  },
  {
    "path": "code/es6/spread-operator.js",
    "chars": 164,
    "preview": "var spread;\n(function (spread) {\n    var list = [\n        1,\n        2\n    ];\n    list = list.concat([3, 4]);\n})(spread "
  },
  {
    "path": "code/es6/spread-operator.ts",
    "chars": 75,
    "preview": "export module spread {\n    var list = [1, 2];\n    list = [...list, 3, 4];\n}"
  },
  {
    "path": "code/es6/template-strings.js",
    "chars": 1501,
    "preview": "exports.templateStrings = '123';\nvar m1;\n(function (m1) {\n    var lyrics = \"Never gonna give you up \\\n\\nNever gonna let "
  },
  {
    "path": "code/es6/template-strings.ts",
    "chars": 1301,
    "preview": "export var templateStrings = '123';\n\nmodule m1 {\n    var lyrics = \"Never gonna give you up \\\n\\nNever gonna let you down\""
  },
  {
    "path": "code/es6/test.js",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "code/es6/test.ts",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "code/es6/tsconfig.json",
    "chars": 3,
    "preview": "{}\n"
  },
  {
    "path": "code/javascript/closure.js",
    "chars": 1148,
    "preview": "\"use strict\";\nfunction outerFunction(arg) {\n    var variableInOuterFunction = arg;\n    function bar() {\n        console."
  },
  {
    "path": "code/javascript/closure.ts",
    "chars": 1194,
    "preview": "function outerFunction(arg) {\n    var variableInOuterFunction = arg;\n\n    function bar() {\n        console.log(variableI"
  },
  {
    "path": "code/javascript/tsconfig.json",
    "chars": 715,
    "preview": "{\n    \"compilerOptions\": {\n        \"target\": \"es5\",\n        \"module\": \"commonjs\",\n        \"moduleResolution\": \"node\",\n  "
  },
  {
    "path": "code/tips/bindIsBad.js",
    "chars": 725,
    "preview": "\"use strict\";\nvar Adder = (function () {\n    function Adder(a) {\n        this.a = a;\n    }\n    Adder.prototype.add = fun"
  },
  {
    "path": "code/tips/bindIsBad.ts",
    "chars": 832,
    "preview": "export var _asdfasdfsadf;\n\nclass Adder {\n    constructor(public a: string) { }\n\n    add(b: string): string {\n        ret"
  },
  {
    "path": "code/tips/currying.js",
    "chars": 132,
    "preview": "\"use strict\";\nvar add = function (x) { return function (y) { return x + y; }; };\nadd(123)(456);\nvar add123 = add(123);\na"
  },
  {
    "path": "code/tips/currying.ts",
    "chars": 221,
    "preview": "export var _asdfasdfasdf;\n\n\n// A function that supports currying\nlet add = (x: number) => (y: number) => x + y;\n\n// Simp"
  },
  {
    "path": "code/tips/lazyObjectLiteralInitialization.js",
    "chars": 636,
    "preview": "\"use strict\";\nvar JS;\n(function (JS) {\n    var foo = {};\n    foo.bar = 123;\n    foo.bas = \"Hello World\";\n})(JS = exports"
  },
  {
    "path": "code/tips/lazyObjectLiteralInitialization.ts",
    "chars": 602,
    "preview": "export namespace JS {\n    let foo = {};\n    foo.bar = 123;\n    foo.bas = \"Hello World\";\n}\n\nexport namespace TS {\n    let"
  },
  {
    "path": "code/tips/mixins.js",
    "chars": 1664,
    "preview": "var __extends = (this && this.__extends) || function (d, b) {\n    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];"
  },
  {
    "path": "code/tips/mixins.ts",
    "chars": 1300,
    "preview": "// Disposable Mixin\nclass Disposable {\n    isDisposed: boolean;\n    dispose() {\n        this.isDisposed = true;\n    }\n\n}"
  },
  {
    "path": "code/tips/nominalTyping.js",
    "chars": 676,
    "preview": "var EnumDriven;\n(function (EnumDriven) {\n    var FooIdBrand;\n    (function (FooIdBrand) {\n    })(FooIdBrand || (FooIdBra"
  },
  {
    "path": "code/tips/nominalTyping.ts",
    "chars": 1537,
    "preview": "namespace Literal {\n  /** Generic Id type */\n  type Id<T extends string> = {\n    type: T,\n    value: string,\n  }\n\n  /** "
  },
  {
    "path": "code/tips/statefulFunctions.js",
    "chars": 294,
    "preview": "var called = (new (function () {\n    function class_1() {\n        var _this = this;\n        this.count = 0;\n        this"
  },
  {
    "path": "code/tips/statefulFunctions.ts",
    "chars": 190,
    "preview": "let {called} = new class {\n    count = 0;\n    called = () => {\n        this.count++;\n        console.log(`Called : ${thi"
  },
  {
    "path": "code/tips/stringEnums.js",
    "chars": 455,
    "preview": "\"use strict\";\nvar Simple;\n(function (Simple) {\n    var Tristate = {\n        False: '',\n        True: '',\n        Unknown"
  },
  {
    "path": "code/tips/stringEnums.ts",
    "chars": 486,
    "preview": "export namespace Simple {\n    let Tristate = {\n        False: '',\n        True: '',\n        Unknown: ''\n    };\n\n    // m"
  },
  {
    "path": "code/tips/tsconfig.json",
    "chars": 849,
    "preview": "{\n    \"compilerOptions\": {\n        \"target\": \"es5\",\n        \"module\": \"commonjs\",\n        \"declaration\": false,\n        "
  },
  {
    "path": "code/types/assertion.js",
    "chars": 672,
    "preview": "exports.asdf = 123;\nvar porting;\n(function (porting) {\n    var foo = {};\n    foo.bar = 123;\n    foo.bas = 'hello';\n})(po"
  },
  {
    "path": "code/types/assertion.ts",
    "chars": 846,
    "preview": "export var asdf = 123;\n\nmodule porting {\n    var foo = {};\n    foo.bar = 123; // error : property 'bar' does not exist o"
  },
  {
    "path": "code/types/callable.ts",
    "chars": 998,
    "preview": "export namespace asdfasdfasdfasdflkjasdflkjasdflkjasdflkjasdf {\n}\n\nnamespace A {\n  interface ReturnString {\n    (): stri"
  },
  {
    "path": "code/types/freshness/freshness.js",
    "chars": 1156,
    "preview": "exports.foo = 123;\nvar first;\n(function (first) {\n    function logName(something) {\n        console.log(something.name);"
  },
  {
    "path": "code/types/freshness/freshness.ts",
    "chars": 2250,
    "preview": "export var foo = 123;\n\nmodule first {\n\tfunction logName(something: { name: string }) {\n\t\tconsole.log(something.name);\n\t}"
  },
  {
    "path": "code/types/freshness/index-signatures.js",
    "chars": 1684,
    "preview": "var a;\n(function (a) {\n    var foo = {};\n    foo['Hello'] = 'World';\n    console.log(foo['Hello']);\n})(a || (a = {}));\nv"
  },
  {
    "path": "code/types/freshness/index-signatures.ts",
    "chars": 3049,
    "preview": "module a {\n  let foo: any = {};\n  foo['Hello'] = 'World';\n  console.log(foo['Hello']); // World\n}\nmodule b {\n  class Foo"
  },
  {
    "path": "code/types/freshness/tsconfig.json",
    "chars": 690,
    "preview": "{\n    \"version\": \"1.5.0-beta\",\n    \"compilerOptions\": {\n        \"target\": \"es5\",\n        \"module\": \"commonjs\",\n        \""
  },
  {
    "path": "code/types/functions.js",
    "chars": 1924,
    "preview": "\"use strict\";\nvar parameter;\n(function (parameter) {\n    var sampleVariable;\n    function foo(sampleParameter) { }\n})(pa"
  },
  {
    "path": "code/types/functions.ts",
    "chars": 2151,
    "preview": "export namespace asdfasdfasdfasdflkjasdflkjasdflkjasdflkjasdf {\n}\n\nnamespace parameter {\n    // variable annotation\n    "
  },
  {
    "path": "code/types/generics.js",
    "chars": 1371,
    "preview": "var aaa;\n(function (aaa) {\n    var Queue = (function () {\n        function Queue() {\n            var _this = this;\n     "
  },
  {
    "path": "code/types/generics.ts",
    "chars": 1706,
    "preview": "module aaa {\n  class Queue {\n    private data = [];\n    push = (item) => this.data.push(item);\n    pop = () => this.data"
  },
  {
    "path": "code/types/interfaces.js",
    "chars": 352,
    "preview": "var Implement;\n(function (Implement) {\n    var MyPoint = (function () {\n        function MyPoint() {\n        }\n        r"
  },
  {
    "path": "code/types/interfaces.ts",
    "chars": 391,
    "preview": "namespace Implement {\n    interface Point {\n        x: number; y: number;\n    }\n\n    class MyPoint implements Point {\n  "
  },
  {
    "path": "code/types/keyof.ts",
    "chars": 212,
    "preview": "namespace Test {\n  const colors = {\n    red: 'red',\n    blue: 'blue'\n  }\n  type Colors = keyof typeof colors; \n\n  let co"
  },
  {
    "path": "code/types/lib/exclude/nolibd.js",
    "chars": 41,
    "preview": "var foo = 123;\nvar bar = foo.toString();\n"
  },
  {
    "path": "code/types/lib/exclude/nolibd.ts",
    "chars": 97,
    "preview": "var foo = 123; \nvar bar = foo.toString(); // Property 'toString' does not exist on type 'number'."
  },
  {
    "path": "code/types/lib/exclude/tsconfig.json",
    "chars": 55,
    "preview": "{\n    \"compilerOptions\":{\n        \"noLib\": true\n    }\n}"
  },
  {
    "path": "code/types/lib/usage/libd.js",
    "chars": 409,
    "preview": "var foo = 123;\nvar bar = foo.toString();\nvar test = window;\nwindow.helloWorld = function () { return console.log('hello "
  },
  {
    "path": "code/types/lib/usage/libd.ts",
    "chars": 791,
    "preview": "var foo = 123;\nvar bar = foo.toString();\n\nvar test = window;\n\ninterface Window {\n    helloWorld(): void;\n}\n\n// Add it at"
  },
  {
    "path": "code/types/lib/usage/tsconfig.json",
    "chars": 33,
    "preview": "{\n    \"compilerOptions\":{\n    }\n}"
  },
  {
    "path": "code/types/libd.js",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "code/types/literal-types.js",
    "chars": 304,
    "preview": "\"use strict\";\nvar Simple;\n(function (Simple) {\n    var foo;\n    foo = 'Bar';\n})(Simple = exports.Simple || (exports.Simp"
  },
  {
    "path": "code/types/literal-types.ts",
    "chars": 1022,
    "preview": "export namespace Simple {\n  let foo: 'Hello';\n  foo = 'Bar'; // Error: \"Bar\" is not assignable to type \"Hello\"\n}\n\n\nexpor"
  },
  {
    "path": "code/types/migrating/migrating.js",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "code/types/migrating/migrating.ts",
    "chars": 46,
    "preview": "declare var $: any;\ndeclare type JQuery = any;"
  },
  {
    "path": "code/types/migrating/tsconfig.json",
    "chars": 2,
    "preview": "{}"
  },
  {
    "path": "code/types/readonly.js",
    "chars": 2686,
    "preview": "\"use strict\";\nvar __extends = (this && this.__extends) || function (d, b) {\n    for (var p in b) if (b.hasOwnProperty(p)"
  },
  {
    "path": "code/types/readonly.ts",
    "chars": 2847,
    "preview": "export namespace Simple {\n    function foo(config: {\n        readonly bar: number,\n        readonly bas: number\n    }) {"
  },
  {
    "path": "code/types/stringLiteralType.js",
    "chars": 304,
    "preview": "\"use strict\";\nvar Simple;\n(function (Simple) {\n    var foo;\n    foo = 'Bar';\n})(Simple = exports.Simple || (exports.Simp"
  },
  {
    "path": "code/types/tsconfig.json",
    "chars": 584,
    "preview": "{\n    \"compilerOptions\": {\n        \"target\": \"es5\",\n        \"module\": \"commonjs\",\n        \"moduleResolution\": \"node\",\n  "
  },
  {
    "path": "code/types/type-compatibility.js",
    "chars": 3361,
    "preview": "\"use strict\";\nvar __extends = (this && this.__extends) || function (d, b) {\n    for (var p in b) if (b.hasOwnProperty(p)"
  },
  {
    "path": "code/types/type-compatibility.ts",
    "chars": 3254,
    "preview": "export namespace InCompat {\n    let str: string = \"Hello\";\n    let num: number = 123;\n\n    str = num; // ERROR: `number`"
  },
  {
    "path": "code/types/type-inference.js",
    "chars": 2305,
    "preview": "var Definition;\n(function (Definition) {\n    var foo = 123;\n    var bar = \"Hello\";\n    foo = bar;\n})(Definition || (Defi"
  },
  {
    "path": "code/types/type-inference.ts",
    "chars": 2417,
    "preview": "namespace Definition {\n    let foo = 123; // foo is a `number`\n    let bar = \"Hello\"; // bar is a `string`\n    foo = bar"
  },
  {
    "path": "code/types/typeGuard.js",
    "chars": 2226,
    "preview": "\"use strict\";\nvar quick;\n(function (quick) {\n    function doSomething(x) {\n        if (typeof x === 'string') {\n        "
  },
  {
    "path": "code/types/typeGuard.ts",
    "chars": 2264,
    "preview": "export namespace quick {\n    function doSomething(x: number | string) {\n        if (typeof x === 'string') { // Within t"
  },
  {
    "path": "code/types/types.js",
    "chars": 4063,
    "preview": "var typeannotations;\n(function (typeannotations) {\n    var num = 123;\n    function identity(num) {\n        return num;\n "
  },
  {
    "path": "code/types/types.ts",
    "chars": 4377,
    "preview": "export module typeannotations {\n    var num: number = 123;\n    function identity(num: number): number {\n        return n"
  },
  {
    "path": "docs/arrow-functions.md",
    "chars": 6279,
    "preview": "* [Arrow Functions](#arrow-functions)\n* [Tip: Arrow Function Need](#tip-arrow-function-need)\n* [Tip: Arrow Function Dang"
  },
  {
    "path": "docs/async-await.md",
    "chars": 9105,
    "preview": "## Async Await\n\n> [A PRO egghead video course that covers the same material](https://egghead.io/courses/async-await-usin"
  },
  {
    "path": "docs/classes-emit.md",
    "chars": 6472,
    "preview": "#### 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"
  },
  {
    "path": "docs/classes.md",
    "chars": 6141,
    "preview": "### Classes\nThe reason why it's important to have classes in JavaScript as a first class item is that:\n\n1. [Classes offe"
  },
  {
    "path": "docs/compiler/ast-tip-children.md",
    "chars": 1746,
    "preview": "### AST Tip: Visit Children\n\nThere is a utility function `ts.forEachChild` that allows you to visit all the child nodes "
  },
  {
    "path": "docs/compiler/ast-tip-syntaxkind.md",
    "chars": 826,
    "preview": "### AST Tip: SyntaxKind\n\n`SyntaxKind` is defined as a `const enum`, here is a sample:\n\n```ts\nexport const enum SyntaxKin"
  },
  {
    "path": "docs/compiler/ast-trivia.md",
    "chars": 2446,
    "preview": "### Trivia\nTrivia (called that because it's `trivial`) represent the parts of the source text that are largely insignifi"
  },
  {
    "path": "docs/compiler/ast.md",
    "chars": 943,
    "preview": "## Node\nThe basic building block of the Abstract Syntax Tree (AST). In general a `Node` represents non-terminals in the "
  },
  {
    "path": "docs/compiler/binder-container.md",
    "chars": 5771,
    "preview": "### Container\n\nAn AST node can be a container. This determines the kinds of `SymbolTables` the Node and associated Symbo"
  },
  {
    "path": "docs/compiler/binder-declarations.md",
    "chars": 1394,
    "preview": "### Symbols and Declarations\nLinking between a `node` and a `symbol` is performed by a few functions. One function that "
  },
  {
    "path": "docs/compiler/binder-diagnostics.md",
    "chars": 1810,
    "preview": "### Binder Error Reporting\n\nBinding errors are added to the sourceFile's list of `bindDiagnostics`.\n\nAn example error de"
  },
  {
    "path": "docs/compiler/binder-functions.md",
    "chars": 2183,
    "preview": "### Binder function\nTwo critical binder functions are `bindSourceFile` and `mergeSymbolTable`. We will take a look at th"
  },
  {
    "path": "docs/compiler/binder-symbolflags.md",
    "chars": 5047,
    "preview": "### SymbolFlags\nSymbols have `SymbolFlags`. Below we have them in their verbatim, as of TypeScript 2.2\n\n```ts\n    export"
  },
  {
    "path": "docs/compiler/binder-symboltable.md",
    "chars": 4947,
    "preview": "### SymbolTable\n\nSymbolTable is implemented as a simple HashMap. Here is the interface (`types.ts`):\n\n```ts\ninterface Sy"
  },
  {
    "path": "docs/compiler/binder.md",
    "chars": 1931,
    "preview": "## Binder\nMost JavaScript transpilers out there are simpler than TypeScript because they provide little in the way of co"
  },
  {
    "path": "docs/compiler/checker-diagnostics.md",
    "chars": 425,
    "preview": "### Checker error reporting\nThe checker uses the local `error` function to report errors. Here is the function:\n\n```ts\nf"
  },
  {
    "path": "docs/compiler/checker-global.md",
    "chars": 445,
    "preview": "### Global Namespace Merging\nWithin `initializeTypeChecker` the following code exists:\n\n```ts\n// Initialize global symbo"
  },
  {
    "path": "docs/compiler/checker.md",
    "chars": 1639,
    "preview": "## Checker\nLike we mentioned before *checker* is the thing that makes TypeScript uniquely more powerful than *just anoth"
  },
  {
    "path": "docs/compiler/contributing.md",
    "chars": 2952,
    "preview": "## Contributing\n\nTypeScript is [OSS and on GitHub](https://github.com/Microsoft/TypeScript) and the team welcomes commun"
  },
  {
    "path": "docs/compiler/emitter-functions.md",
    "chars": 15004,
    "preview": "### `emitFiles`\nDefined in `emitter.ts` here is the function signature:\n```ts\n// targetSourceFile is when users only wan"
  },
  {
    "path": "docs/compiler/emitter-sourcemaps.md",
    "chars": 3337,
    "preview": "### Emitter SourceMaps\n\nWe said that the bulk of the `emitter.ts` is the local function `emitJavaScript` (we showed the "
  },
  {
    "path": "docs/compiler/emitter.md",
    "chars": 898,
    "preview": "## Emitter\nThere are two `emitters` provided with the TypeScript compiler:\n\n* `emitter.ts`: this is the emitter you are "
  },
  {
    "path": "docs/compiler/make-global.md",
    "chars": 504,
    "preview": "## Make TypeScript Global\n\nTypeScript is written using a `namespace ts`. And then the whole compiler is compiled into a "
  },
  {
    "path": "docs/compiler/overview.md",
    "chars": 2900,
    "preview": "# Compiler\nThe TypeScript compiler source is located under the [`src/compiler`](https://github.com/Microsoft/TypeScript/"
  },
  {
    "path": "docs/compiler/parser-functions.md",
    "chars": 2526,
    "preview": "### Parser Functions\n\nAs mentioned `parseSourceFile` sets up the initial state and passes the work onto `parseSourceFile"
  },
  {
    "path": "docs/compiler/parser.md",
    "chars": 2403,
    "preview": "## Parser\nThe sourcecode for the TypeScript parser is located entirely in `parser.ts`. Scanner is *controlled* internall"
  },
  {
    "path": "docs/compiler/program.md",
    "chars": 862,
    "preview": "## Program\n\nDefined in `program.ts`. The compilation context ([a concept we covered previously](../project/compilation-c"
  },
  {
    "path": "docs/compiler/scanner.md",
    "chars": 2683,
    "preview": "## Scanner\nThe source code for the TypeScript scanner is located entirely in `scanner.ts`. Scanner is *controlled* inter"
  },
  {
    "path": "docs/compiler-options.md",
    "chars": 57,
    "preview": "// mention Pinned comments\n\n```ts\n/*!\n * License\n */\n```\n"
  },
  {
    "path": "docs/const.md",
    "chars": 1856,
    "preview": "### const\n\n`const` is a very welcomed addition offered by ES6 / TypeScript. It allows you to be immutable with variables"
  },
  {
    "path": "docs/declaration.md",
    "chars": 23,
    "preview": "analogy with c headers\n"
  },
  {
    "path": "docs/destructuring.md",
    "chars": 3890,
    "preview": "### Destructuring\n\nTypeScript supports the following forms of Destructuring (literally named after de-structuring i.e. b"
  },
  {
    "path": "docs/enums.md",
    "chars": 9996,
    "preview": "* [Enums](#enums)\n* [Number Enums and numbers](#number-enums-and-numbers)\n* [Number Enums and strings](#number-enums-and"
  },
  {
    "path": "docs/errors/common-errors.md",
    "chars": 1865,
    "preview": "# Common Errors\nIn this section we explain a number of common error codes that users experience in the real world.\n\n## T"
  },
  {
    "path": "docs/errors/interpreting-errors.md",
    "chars": 3195,
    "preview": "# Interpreting Errors \nSince TypeScript is a heavily focused *Developer Help* oriented programming language, its errors "
  },
  {
    "path": "docs/errors/main.md",
    "chars": 138,
    "preview": "# Errors \nIn this section we discuss how to read and understand TypeScript errors. We follow this with common errors and"
  },
  {
    "path": "docs/for...of.md",
    "chars": 2498,
    "preview": "### for...of\nA common error experienced by beginning JavaScript developers is that `for...in` for an array does not iter"
  },
  {
    "path": "docs/future-javascript.md",
    "chars": 649,
    "preview": "# Future JavaScript: Now\nOne of the main selling points of TypeScript is that it allows you to use a bunch of features f"
  },
  {
    "path": "docs/generators.md",
    "chars": 4873,
    "preview": "## Generators\n\n`function *` is the syntax used to create a *generator function*. Calling a generator function returns a "
  },
  {
    "path": "docs/getting-started.md",
    "chars": 1994,
    "preview": "* [Getting Started with TypeScript](#getting-started-with-typescript)\n* [TypeScript Version](#typescript-version)\n\n# Get"
  },
  {
    "path": "docs/iterators.md",
    "chars": 5462,
    "preview": "### Iterators\n\nIterator itself is not a TypeScript or ES6 feature, Iterator is a\nBehavioral Design Pattern common for Ob"
  },
  {
    "path": "docs/javascript/closure.md",
    "chars": 2150,
    "preview": "## Closure\n\nThe best thing that JavaScript ever got was closures. A function in JavaScript has access to any variables d"
  },
  {
    "path": "docs/javascript/equality.md",
    "chars": 2021,
    "preview": "## Equality\n\nOne thing to be careful about in JavaScript is the difference between `==` and `===`. As JavaScript tries t"
  },
  {
    "path": "docs/javascript/null-undefined.md",
    "chars": 5010,
    "preview": "## Null and Undefined\n\n> [Free youtube video on the subject](https://www.youtube.com/watch?v=kaUfBNzuUAI)\n\nJavaScript (a"
  },
  {
    "path": "docs/javascript/number.md",
    "chars": 5269,
    "preview": "## Number\nWhenever you are handling numbers in any programming language you need to be aware of the idiosyncrasies of ho"
  },
  {
    "path": "docs/javascript/recap.md",
    "chars": 2398,
    "preview": "# Your JavaScript is TypeScript\n\nThere were (and will continue to be) a lot of competitors in *Some syntax* to *JavaScri"
  },
  {
    "path": "docs/javascript/references.md",
    "chars": 530,
    "preview": "## References\n\nBeyond literals, any Object in JavaScript (including functions, arrays, regexp etc) are references. This "
  },
  {
    "path": "docs/javascript/this.md",
    "chars": 562,
    "preview": "## this\n\nAny access to `this` keyword within a function is controlled by how the function is actually called. It is comm"
  },
  {
    "path": "docs/javascript/truthy.md",
    "chars": 1863,
    "preview": "## Truthy\n\nJavaScript has a concept of `truthy` i.e. things that evaluate like `true` would in certain positions (e.g. `"
  },
  {
    "path": "docs/jsx/others.md",
    "chars": 2142,
    "preview": "# Non React JSX\n\n[![DesignTSX](https://raw.githubusercontent.com/basarat/typescript-book/master/images/designtsx-banner."
  },
  {
    "path": "docs/jsx/react.md",
    "chars": 8585,
    "preview": "# React JSX\n\n> [Free series of youtube videos on React / TypeScript best practices](https://www.youtube.com/watch?v=7EW6"
  },
  {
    "path": "docs/jsx/tsx.md",
    "chars": 1390,
    "preview": "# JSX Support\n\n[![DesignTSX](https://raw.githubusercontent.com/basarat/typescript-book/master/images/designtsx-banner.pn"
  },
  {
    "path": "docs/let.md",
    "chars": 4728,
    "preview": "### let\n\n`var` Variables in JavaScript are *function scoped*. This is different from many other languages (C# / Java etc"
  },
  {
    "path": "docs/npm/index.md",
    "chars": 4918,
    "preview": "# NPM \n\n> Fun fact `npm` is [not an acronym](https://twitter.com/npmjs/status/347057301401763840) so it doesn't expand t"
  },
  {
    "path": "docs/options/intro.md",
    "chars": 1031,
    "preview": "# Convenience vs. Soundness\n\nThere are a few things that TypeScript prevents you from doing out of the box e.g. using a "
  },
  {
    "path": "docs/options/noImplicitAny.md",
    "chars": 1122,
    "preview": "# noImplicitAny\n\nThere are some things that cannot be inferred or inferring them might result in unexpected errors. A fi"
  },
  {
    "path": "docs/options/strictNullChecks.md",
    "chars": 3339,
    "preview": "# `strictNullChecks`\n\nBy default `null` and `undefined` are assignable to all types in TypeScript e.g.\n\n```ts\nlet foo: n"
  },
  {
    "path": "docs/project/compilation-context.md",
    "chars": 438,
    "preview": "## Compilation Context\nThe compilation context is basically just a fancy term for grouping of the files that TypeScript "
  },
  {
    "path": "docs/project/declarationspaces.md",
    "chars": 1859,
    "preview": "## Declaration Spaces\n\nThere are two declaration spaces in TypeScript: the *variable* declaration space and the *type* d"
  },
  {
    "path": "docs/project/dynamic-import-expressions.md",
    "chars": 3722,
    "preview": "## Dynamic import expressions \n\n**Dynamic import expressions** are a new feature and part of **ECMAScript** that allows "
  },
  {
    "path": "docs/project/external-modules.md",
    "chars": 10212,
    "preview": "## External modules\nThere is a lot of power and usability packed into the TypeScript external module pattern. Here we di"
  },
  {
    "path": "docs/project/files.md",
    "chars": 678,
    "preview": "## Which files?\n\nUse `include` and `exclude` to specify files / folders / globs. E.g.:\n\n\n```json\n{\n    \"include\":[\n     "
  },
  {
    "path": "docs/project/globals.md",
    "chars": 1169,
    "preview": "# global.d.ts\n\nWe discussed *global* vs. *file* modules when covering [projects](./modules.md) and recommended using fil"
  },
  {
    "path": "docs/project/module-resolution.md",
    "chars": 2841,
    "preview": "# TypeScript Module Resolution\n\nTypeScript's module resolution tries to model and support the real world modules systems"
  },
  {
    "path": "docs/project/modules.md",
    "chars": 1597,
    "preview": "## Modules\n\n### Global Module\n\nBy default when you start typing code in a new TypeScript file your code is in a *global*"
  },
  {
    "path": "docs/project/namespaces.md",
    "chars": 1799,
    "preview": "## Namespaces\nNamespaces provide you with a convenient syntax around a common pattern used in JavaScript:\n\n```ts\n(functi"
  },
  {
    "path": "docs/project/project.md",
    "chars": 229,
    "preview": "# Project\n\nTo create a successful project using TypeScript you need to understand the various project organization langu"
  },
  {
    "path": "docs/project/tsconfig.md",
    "chars": 5945,
    "preview": "### 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 e"
  },
  {
    "path": "docs/promise.md",
    "chars": 16231,
    "preview": "## Promise\n\nThe `Promise` class is something that exists in many modern JavaScript engines and can be easily [polyfilled"
  },
  {
    "path": "docs/quick/browser.md",
    "chars": 4307,
    "preview": "# TypeScript in the browser\n\n[![DesignTSX](https://raw.githubusercontent.com/basarat/typescript-book/master/images/desig"
  },
  {
    "path": "docs/quick/library.md",
    "chars": 3720,
    "preview": "# Creating TypeScript node modules\n\n* [A lesson on creating TypeScript node modules](https://egghead.io/lessons/typescri"
  },
  {
    "path": "docs/quick/nodejs.md",
    "chars": 1882,
    "preview": "# TypeScript with Node.js\nTypeScript has had *first class* support for Node.js since inception. Here's how to setup a qu"
  },
  {
    "path": "docs/rest-parameters.md",
    "chars": 488,
    "preview": "### Rest Parameters\nRest parameters (denoted by `...argumentName` for the last argument) allow you to quickly accept mul"
  },
  {
    "path": "docs/spread-operator.md",
    "chars": 2695,
    "preview": "### Spread Operator\n\nThe main objective of the spread operator is to *spread* the elements of an array or object. This i"
  },
  {
    "path": "docs/staging/async-await.md",
    "chars": 18,
    "preview": "### Async - Await\n"
  },
  {
    "path": "docs/staging/generators.md",
    "chars": 2014,
    "preview": "### Generators\nAlso called `function *`, generators allow you to create functions whose execution can be paused and then"
  },
  {
    "path": "docs/state/mobx.md",
    "chars": 139,
    "preview": "## MobX \n\n> [PRO Egghead course on MobX TypeScript React](https://egghead.io/courses/develop-react-applications-with-mob"
  },
  {
    "path": "docs/styleguide/sample.js",
    "chars": 344,
    "preview": "\"use strict\";\nvar formatting;\n(function (formatting) {\n    var FooVar;\n    function BarFunc() { }\n})(formatting || (form"
  },
  {
    "path": "docs/styleguide/sample.ts",
    "chars": 171,
    "preview": "export var test;\n\nnamespace formatting {\n    var FooVar;\n    function BarFunc() { }\n}\n\nnamespace asdfasdf {\n    class Fo"
  }
]

// ... and 61 more files (download for full content)

About this extraction

This page contains the full source code of the basarat/typescript-book GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 261 files (627.9 KB), approximately 164.3k tokens, and a symbol index with 397 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!