├── .gitignore
├── .travis.yml
├── .gitattributes
├── pages
├── Typings for NPM Packages.md
├── Writing Declaration Files.md
├── declaration files
│ ├── Templates.md
│ ├── templates
│ │ ├── global-plugin.d.ts.md
│ │ ├── global-modifying-module.d.ts.md
│ │ ├── module-plugin.d.ts.md
│ │ ├── module.d.ts.md
│ │ ├── module-class.d.ts.md
│ │ ├── global.d.ts.md
│ │ └── module-function.d.ts.md
│ ├── Consumption.md
│ ├── Introduction.md
│ ├── Publishing.md
│ ├── By Example.md
│ ├── Do's and Don'ts.md
│ └── Deep Dive.md
├── tutorials
│ ├── Angular.md
│ ├── TypeScript in 5 minutes.md
│ └── React & Webpack.md
├── release notes
│ ├── TypeScript 1.1.md
│ ├── TypeScript 1.3.md
│ ├── TypeScript 2.5.md
│ ├── TypeScript 2.4.md
│ ├── TypeScript 1.7.md
│ ├── TypeScript 1.4.md
│ ├── TypeScript 2.2.md
│ └── TypeScript 2.3.md
├── Iterators and Generators.md
├── Nightly Builds.md
├── Symbols.md
├── Type Inference.md
├── Mixins.md
├── Triple-Slash Directives.md
├── Namespaces and Modules.md
├── Integrating with Build Tools.md
├── Type Checking JavaScript Files.md
├── tsconfig.json.md
├── Compiler Options in MSBuild.md
├── Enums.md
├── Basic Types.md
├── Namespaces.md
└── Type Compatibility.md
├── assets
└── images
│ └── tutorials
│ └── aspnet
│ ├── new-folder.png
│ ├── new-item.png
│ ├── open-index.png
│ ├── src-folder.png
│ ├── new-tsconfig.png
│ ├── paused-demo.png
│ ├── running-demo.png
│ ├── new-asp-project.png
│ ├── scripts-folder.png
│ ├── task-runner-explorer.png
│ ├── install-nuget-packages.png
│ ├── new-asp-project-empty.png
│ ├── new-asp-project-empty-17.PNG
│ ├── packageinstaller-angular2.png
│ ├── packageinstaller-es6-shim.png
│ ├── packageinstaller-systemjs.png
│ └── packageinstaller-typings.png
├── CONTRIBUTING.md
├── README.md
├── package.json
├── pull_request_template.md
└── lint.js
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | .vscode
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - "node"
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Normalize line endings for all text files.
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/pages/Typings for NPM Packages.md:
--------------------------------------------------------------------------------
1 | > ## This page has been moved to [Publishing](./declaration files/Publishing.md)
2 |
--------------------------------------------------------------------------------
/pages/Writing Declaration Files.md:
--------------------------------------------------------------------------------
1 | > ## This page has been moved to [Publishing](./declaration files/Introduction.md)
2 |
--------------------------------------------------------------------------------
/assets/images/tutorials/aspnet/new-folder.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ry/TypeScript-Handbook/HEAD/assets/images/tutorials/aspnet/new-folder.png
--------------------------------------------------------------------------------
/assets/images/tutorials/aspnet/new-item.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ry/TypeScript-Handbook/HEAD/assets/images/tutorials/aspnet/new-item.png
--------------------------------------------------------------------------------
/assets/images/tutorials/aspnet/open-index.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ry/TypeScript-Handbook/HEAD/assets/images/tutorials/aspnet/open-index.png
--------------------------------------------------------------------------------
/assets/images/tutorials/aspnet/src-folder.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ry/TypeScript-Handbook/HEAD/assets/images/tutorials/aspnet/src-folder.png
--------------------------------------------------------------------------------
/assets/images/tutorials/aspnet/new-tsconfig.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ry/TypeScript-Handbook/HEAD/assets/images/tutorials/aspnet/new-tsconfig.png
--------------------------------------------------------------------------------
/assets/images/tutorials/aspnet/paused-demo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ry/TypeScript-Handbook/HEAD/assets/images/tutorials/aspnet/paused-demo.png
--------------------------------------------------------------------------------
/assets/images/tutorials/aspnet/running-demo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ry/TypeScript-Handbook/HEAD/assets/images/tutorials/aspnet/running-demo.png
--------------------------------------------------------------------------------
/assets/images/tutorials/aspnet/new-asp-project.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ry/TypeScript-Handbook/HEAD/assets/images/tutorials/aspnet/new-asp-project.png
--------------------------------------------------------------------------------
/assets/images/tutorials/aspnet/scripts-folder.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ry/TypeScript-Handbook/HEAD/assets/images/tutorials/aspnet/scripts-folder.png
--------------------------------------------------------------------------------
/assets/images/tutorials/aspnet/task-runner-explorer.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ry/TypeScript-Handbook/HEAD/assets/images/tutorials/aspnet/task-runner-explorer.png
--------------------------------------------------------------------------------
/assets/images/tutorials/aspnet/install-nuget-packages.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ry/TypeScript-Handbook/HEAD/assets/images/tutorials/aspnet/install-nuget-packages.png
--------------------------------------------------------------------------------
/assets/images/tutorials/aspnet/new-asp-project-empty.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ry/TypeScript-Handbook/HEAD/assets/images/tutorials/aspnet/new-asp-project-empty.png
--------------------------------------------------------------------------------
/assets/images/tutorials/aspnet/new-asp-project-empty-17.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ry/TypeScript-Handbook/HEAD/assets/images/tutorials/aspnet/new-asp-project-empty-17.PNG
--------------------------------------------------------------------------------
/assets/images/tutorials/aspnet/packageinstaller-angular2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ry/TypeScript-Handbook/HEAD/assets/images/tutorials/aspnet/packageinstaller-angular2.png
--------------------------------------------------------------------------------
/assets/images/tutorials/aspnet/packageinstaller-es6-shim.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ry/TypeScript-Handbook/HEAD/assets/images/tutorials/aspnet/packageinstaller-es6-shim.png
--------------------------------------------------------------------------------
/assets/images/tutorials/aspnet/packageinstaller-systemjs.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ry/TypeScript-Handbook/HEAD/assets/images/tutorials/aspnet/packageinstaller-systemjs.png
--------------------------------------------------------------------------------
/assets/images/tutorials/aspnet/packageinstaller-typings.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ry/TypeScript-Handbook/HEAD/assets/images/tutorials/aspnet/packageinstaller-typings.png
--------------------------------------------------------------------------------
/pages/declaration files/Templates.md:
--------------------------------------------------------------------------------
1 | * [global-modifying-module.d.ts](./templates/global-modifying-module.d.ts.md)
2 | * [global-plugin.d.ts](./templates/global-plugin.d.ts.md)
3 | * [global.d.ts](./templates/global.d.ts.md)
4 | * [module-class.d.ts](./templates/module-class.d.ts.md)
5 | * [module-function.d.ts](./templates/module-function.d.ts.md)
6 | * [module-plugin.d.ts](./templates/module-plugin.d.ts.md)
7 | * [module.d.ts](./templates/module.d.ts.md)
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | ## Contributing
2 |
3 | TypeScript-Handbook is accepting contributions. If you've submitted a PR for an existing issue, please post a comment in the issue to avoid duplication of effort.
4 |
5 | ## Housekeeping
6 |
7 | Your pull request should:
8 |
9 | * Include a description of what your change intends to do.
10 | * Have a clear commit messages
11 | * e.g. "New Topic", "Fix typo", "Add code samples"
12 | * For code samples, please make sure they compile against the latest released TypeScript compiler version.
13 |
--------------------------------------------------------------------------------
/pages/tutorials/Angular.md:
--------------------------------------------------------------------------------
1 | Angular is a modern framework built entirely in TypeScript, and as a result, using TypeScript with Angular provides a seamless experience.
2 |
3 | The Angular documentation not only supports TypeScript as a first-class citizen, but uses it as its primary language.
4 | With this in mind, [Angular's site](https://angular.io) will always be the most up-to-date reference for using Angular with TypeScript.
5 |
6 | Check out the [quick start guide here](https://angular.io/docs/ts/latest/quickstart.html) to start learning Angular now!
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # TypeScript-Handbook
2 |
3 | [](https://travis-ci.org/Microsoft/TypeScript-Handbook)
4 |
5 | The TypeScript Handbook is a comprehensive guide to the TypeScript language.
6 | It is meant to be read online at [the TypeScript website](https://www.typescriptlang.org/docs/handbook/basic-types.html) or [directly from this repository](./pages/Basic%20Types.md).
7 |
8 | For a more formal description of the language, see the [latest TypeScript Language Specification](https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md).
9 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "typescript-handbook",
3 | "version": "1.0.0",
4 | "description": "The TypeScript Handbook is a comprehensive guide to the TypeScript language",
5 | "main": "none",
6 | "scripts": {
7 | "test": "node lint.js"
8 | },
9 | "repository": {
10 | "type": "git",
11 | "url": "git+https://github.com/Microsoft/TypeScript-Handbook.git"
12 | },
13 | "author": "",
14 | "license": "Apache-2.0",
15 | "bugs": {
16 | "url": "https://github.com/Microsoft/TypeScript-Handbook/issues"
17 | },
18 | "homepage": "https://github.com/Microsoft/TypeScript-Handbook#readme",
19 | "devDependencies": {
20 | "glob": "^5.0.15",
21 | "markdownlint": "latest"
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/pull_request_template.md:
--------------------------------------------------------------------------------
1 |
16 |
17 | Fixes #
18 |
--------------------------------------------------------------------------------
/pages/release notes/TypeScript 1.1.md:
--------------------------------------------------------------------------------
1 | # Performance Improvements
2 |
3 | The 1.1 compiler is typically around 4x faster than any previous release. See [this blog post for some impressive charts.](http://blogs.msdn.com/b/typescript/archive/2014/10/06/announcing-typescript-1-1-ctp.aspx)
4 |
5 | # Better Module Visibility Rules
6 |
7 | TypeScript now only strictly enforces the visibility of types in modules if the `--declaration` flag is provided. This is very useful for Angular scenarios, for example:
8 |
9 | ```ts
10 | module MyControllers {
11 | interface ZooScope extends ng.IScope {
12 | animals: Animal[];
13 | }
14 | export class ZooController {
15 | // Used to be an error (cannot expose ZooScope), but now is only
16 | // an error when trying to generate .d.ts files
17 | constructor(public $scope: ZooScope) { }
18 | /* more code */
19 | }
20 | }
21 | ```
--------------------------------------------------------------------------------
/pages/declaration files/templates/global-plugin.d.ts.md:
--------------------------------------------------------------------------------
1 | ```ts
2 | // Type definitions for [~THE LIBRARY NAME~] [~OPTIONAL VERSION NUMBER~]
3 | // Project: [~THE PROJECT NAME~]
4 | // Definitions by: [~YOUR NAME~] <[~A URL FOR YOU~]>
5 |
6 | /*~ This template shows how to write a global plugin. */
7 |
8 | /*~ Write a declaration for the original type and add new members.
9 | *~ For example, this adds a 'toBinaryString' method with to overloads to
10 | *~ the built-in number type.
11 | */
12 | interface Number {
13 | toBinaryString(opts?: MyLibrary.BinaryFormatOptions): string;
14 | toBinaryString(callback: MyLibrary.BinaryFormatCallback, opts?: MyLibrary.BinaryFormatOptions): string;
15 | }
16 |
17 | /*~ If you need to declare several types, place them inside a namespace
18 | *~ to avoid adding too many things to the global namespace.
19 | */
20 | declare namespace MyLibrary {
21 | type BinaryFormatCallback = (n: number) => string;
22 | interface BinaryFormatOptions {
23 | prefix?: string;
24 | padding: number;
25 | }
26 | }
27 | ```
--------------------------------------------------------------------------------
/pages/declaration files/templates/global-modifying-module.d.ts.md:
--------------------------------------------------------------------------------
1 | ```ts
2 | // Type definitions for [~THE LIBRARY NAME~] [~OPTIONAL VERSION NUMBER~]
3 | // Project: [~THE PROJECT NAME~]
4 | // Definitions by: [~YOUR NAME~] <[~A URL FOR YOU~]>
5 |
6 | /*~ This is the global-modifying module template file. You should rename it to index.d.ts
7 | *~ and place it in a folder with the same name as the module.
8 | *~ For example, if you were writing a file for "super-greeter", this
9 | *~ file should be 'super-greeter/index.d.ts'
10 | */
11 |
12 | /*~ Note: If your global-modifying module is callable or constructable, you'll
13 | *~ need to combine the patterns here with those in the module-class or module-function
14 | *~ template files
15 | */
16 | declare global {
17 | /*~ Here, declare things that go in the global namespace, or augment
18 | *~ existing declarations in the global namespace
19 | */
20 | interface String {
21 | fancyFormat(opts: StringFormatOptions): string;
22 | }
23 | }
24 |
25 | /*~ If your module exports types or values, write them as usual */
26 | export interface StringFormatOptions {
27 | fancinessLevel: number;
28 | }
29 |
30 | /*~ For example, declaring a method on the module (in addition to its global side effects) */
31 | export function doSomething(): void;
32 |
33 | /*~ If your module exports nothing, you'll need this line. Otherwise, delete it */
34 | export { };
35 | ```
--------------------------------------------------------------------------------
/pages/declaration files/templates/module-plugin.d.ts.md:
--------------------------------------------------------------------------------
1 | ```ts
2 | // Type definitions for [~THE LIBRARY NAME~] [~OPTIONAL VERSION NUMBER~]
3 | // Project: [~THE PROJECT NAME~]
4 | // Definitions by: [~YOUR NAME~] <[~A URL FOR YOU~]>
5 |
6 | /*~ This is the module plugin template file. You should rename it to index.d.ts
7 | *~ and place it in a folder with the same name as the module.
8 | *~ For example, if you were writing a file for "super-greeter", this
9 | *~ file should be 'super-greeter/index.d.ts'
10 | */
11 |
12 | /*~ On this line, import the module which this module adds to */
13 | import * as m from 'someModule';
14 |
15 | /*~ You can also import other modules if needed */
16 | import * as other from 'anotherModule';
17 |
18 | /*~ Here, declare the same module as the one you imported above */
19 | declare module 'someModule' {
20 | /*~ Inside, add new function, classes, or variables. You can use
21 | *~ unexported types from the original module if needed. */
22 | export function theNewMethod(x: m.foo): other.bar;
23 |
24 | /*~ You can also add new properties to existing interfaces from
25 | *~ the original module by writing interface augmentations */
26 | export interface SomeModuleOptions {
27 | someModuleSetting?: string;
28 | }
29 |
30 | /*~ New types can also be declared and will appear as if they
31 | *~ are in the original module */
32 | export interface MyModulePluginOptions {
33 | size: number;
34 | }
35 | }
36 | ```
--------------------------------------------------------------------------------
/pages/release notes/TypeScript 1.3.md:
--------------------------------------------------------------------------------
1 | # Protected
2 |
3 | The new `protected` modifier in classes works like it does in familiar languages like C++, C#, and Java. A `protected` member of a class is visible only inside subclasses of the class in which it is declared:
4 |
5 | ```ts
6 | class Thing {
7 | protected doSomething() { /* ... */ }
8 | }
9 |
10 | class MyThing extends Thing {
11 | public myMethod() {
12 | // OK, can access protected member from subclass
13 | this.doSomething();
14 | }
15 | }
16 | var t = new MyThing();
17 | t.doSomething(); // Error, cannot call protected member from outside class
18 | ```
19 |
20 | # Tuple types
21 |
22 | Tuple types express an array where the type of certain elements is known, but need not be the same. For example, you may want to represent an array with a `string` at position 0 and a `number` at position 1:
23 |
24 | ```ts
25 | // Declare a tuple type
26 | var x: [string, number];
27 | // Initialize it
28 | x = ['hello', 10]; // OK
29 | // Initialize it incorrectly
30 | x = [10, 'hello']; // Error
31 | ```
32 |
33 | When accessing an element with a known index, the correct type is retrieved:
34 |
35 | ```ts
36 | console.log(x[0].substr(1)); // OK
37 | console.log(x[1].substr(1)); // Error, 'number' does not have 'substr'
38 | ```
39 |
40 | Note that in TypeScript 1.4, when accessing an element outside the set of known indices, a union type is used instead:
41 |
42 | ```ts
43 | x[3] = 'world'; // OK
44 | console.log(x[5].toString()); // OK, 'string' and 'number' both have toString
45 | x[6] = true; // Error, boolean isn't number or string
46 | ```
--------------------------------------------------------------------------------
/pages/declaration files/templates/module.d.ts.md:
--------------------------------------------------------------------------------
1 | ```ts
2 | // Type definitions for [~THE LIBRARY NAME~] [~OPTIONAL VERSION NUMBER~]
3 | // Project: [~THE PROJECT NAME~]
4 | // Definitions by: [~YOUR NAME~] <[~A URL FOR YOU~]>
5 |
6 | /*~ This is the module template file. You should rename it to index.d.ts
7 | *~ and place it in a folder with the same name as the module.
8 | *~ For example, if you were writing a file for "super-greeter", this
9 | *~ file should be 'super-greeter/index.d.ts'
10 | */
11 |
12 | /*~ If this module is a UMD module that exposes a global variable 'myLib' when
13 | *~ loaded outside a module loader environment, declare that global here.
14 | *~ Otherwise, delete this declaration.
15 | */
16 | export as namespace myLib;
17 |
18 | /*~ If this module has methods, declare them as functions like so.
19 | */
20 | export function myMethod(a: string): string;
21 | export function myOtherMethod(a: number): number;
22 |
23 | /*~ You can declare types that are available via importing the module */
24 | export interface someType {
25 | name: string;
26 | length: number;
27 | extras?: string[];
28 | }
29 |
30 | /*~ You can declare properties of the module using const, let, or var */
31 | export const myField: number;
32 |
33 | /*~ If there are types, properties, or methods inside dotted names
34 | *~ of the module, declare them inside a 'namespace'.
35 | */
36 | export namespace subProp {
37 | /*~ For example, given this definition, someone could write:
38 | *~ import { subProp } from 'yourModule';
39 | *~ subProp.foo();
40 | *~ or
41 | *~ import * as yourMod from 'yourModule';
42 | *~ yourMod.subProp.foo();
43 | */
44 | export function foo(): void;
45 | }
46 | ```
--------------------------------------------------------------------------------
/pages/declaration files/templates/module-class.d.ts.md:
--------------------------------------------------------------------------------
1 | ```ts
2 | // Type definitions for [~THE LIBRARY NAME~] [~OPTIONAL VERSION NUMBER~]
3 | // Project: [~THE PROJECT NAME~]
4 | // Definitions by: [~YOUR NAME~] <[~A URL FOR YOU~]>
5 |
6 | /*~ This is the module template file for class modules.
7 | *~ You should rename it to index.d.ts and place it in a folder with the same name as the module.
8 | *~ For example, if you were writing a file for "super-greeter", this
9 | *~ file should be 'super-greeter/index.d.ts'
10 | */
11 |
12 | /*~ Note that ES6 modules cannot directly export class objects.
13 | *~ This file should be imported using the CommonJS-style:
14 | *~ import x = require('someLibrary');
15 | *~
16 | *~ Refer to the documentation to understand common
17 | *~ workarounds for this limitation of ES6 modules.
18 | */
19 |
20 | /*~ If this module is a UMD module that exposes a global variable 'myClassLib' when
21 | *~ loaded outside a module loader environment, declare that global here.
22 | *~ Otherwise, delete this declaration.
23 | */
24 | export as namespace myClassLib;
25 |
26 | /*~ This declaration specifies that the class constructor function
27 | *~ is the exported object from the file
28 | */
29 | export = MyClass;
30 |
31 | /*~ Write your module's methods and properties in this class */
32 | declare class MyClass {
33 | constructor(someParam?: string);
34 |
35 | someProperty: string[];
36 |
37 | myMethod(opts: MyClass.MyClassMethodOptions): number;
38 | }
39 |
40 | /*~ If you want to expose types from your module as well, you can
41 | *~ place them in this block.
42 | */
43 | declare namespace MyClass {
44 | export interface MyClassMethodOptions {
45 | width?: number;
46 | height?: number;
47 | }
48 | }
49 | ```
--------------------------------------------------------------------------------
/pages/declaration files/Consumption.md:
--------------------------------------------------------------------------------
1 | In TypeScript 2.0, it has become significantly easier to consume declaration files, in acquiring, using, and finding them.
2 | This page details exactly how to do all three.
3 |
4 | # Downloading
5 |
6 | Getting type declarations in TypeScript 2.0 and above requires no tools apart from npm.
7 |
8 | As an example, getting the declarations for a library like lodash takes nothing more than the following command
9 |
10 | ```cmd
11 | npm install --save @types/lodash
12 | ```
13 |
14 | It is worth noting that if the npm package already includes its declaration file as described in [Publishing](./Publishing.md), downloading the corresponding `@types` package is not needed.
15 |
16 | # Consuming
17 |
18 | From there you’ll be able to use lodash in your TypeScript code with no fuss.
19 | This works for both modules and global code.
20 |
21 | For example, once you’ve `npm install`-ed your type declarations, you can use imports and write
22 |
23 | ```ts
24 | import * as _ from "lodash";
25 | _.padStart("Hello TypeScript!", 20, " ");
26 | ```
27 |
28 | or if you’re not using modules, you can just use the global variable `_`.
29 |
30 | ```ts
31 | _.padStart("Hello TypeScript!", 20, " ");
32 | ```
33 |
34 | # Searching
35 |
36 | For the most part, type declaration packages should always have the same name as the package name on `npm`, but prefixed with `@types/`,
37 | but if you need, you can check out [https://aka.ms/types](https://aka.ms/types) to find the package for your favorite library.
38 |
39 | > Note: if the declaration file you are searching for is not present, you can always contribute one back and help out the next developer looking for it.
40 | > Please see the DefinitelyTyped [contribution guidelines page](http://definitelytyped.org/guides/contributing.html) for details.
41 |
--------------------------------------------------------------------------------
/pages/declaration files/templates/global.d.ts.md:
--------------------------------------------------------------------------------
1 | ```ts
2 | // Type definitions for [~THE LIBRARY NAME~] [~OPTIONAL VERSION NUMBER~]
3 | // Project: [~THE PROJECT NAME~]
4 | // Definitions by: [~YOUR NAME~] <[~A URL FOR YOU~]>
5 |
6 | /*~ If this library is callable (e.g. can be invoked as myLib(3)),
7 | *~ include those call signatures here.
8 | *~ Otherwise, delete this section.
9 | */
10 | declare function myLib(a: string): string;
11 | declare function myLib(a: number): number;
12 |
13 | /*~ If you want the name of this library to be a valid type name,
14 | *~ you can do so here.
15 | *~
16 | *~ For example, this allows us to write 'var x: myLib';
17 | *~ Be sure this actually makes sense! If it doesn't, just
18 | *~ delete this declaration and add types inside the namespace below.
19 | */
20 | interface myLib {
21 | name: string;
22 | length: number;
23 | extras?: string[];
24 | }
25 |
26 | /*~ If your library has properties exposed on a global variable,
27 | *~ place them here.
28 | *~ You should also place types (interfaces and type alias) here.
29 | */
30 | declare namespace myLib {
31 | //~ We can write 'myLib.timeout = 50;'
32 | let timeout: number;
33 |
34 | //~ We can access 'myLib.version', but not change it
35 | const version: string;
36 |
37 | //~ There's some class we can create via 'let c = new myLib.Cat(42)'
38 | //~ Or reference e.g. 'function f(c: myLib.Cat) { ... }
39 | class Cat {
40 | constructor(n: number);
41 |
42 | //~ We can read 'c.age' from a 'Cat' instance
43 | readonly age: number;
44 |
45 | //~ We can invoke 'c.purr()' from a 'Cat' instance
46 | purr(): void;
47 | }
48 |
49 | //~ We can declare a variable as
50 | //~ 'var s: myLib.CatSettings = { weight: 5, name: "Maru" };'
51 | interface CatSettings {
52 | weight: number;
53 | name: string;
54 | tailLength?: number;
55 | }
56 |
57 | //~ We can write 'const v: myLib.VetID = 42;'
58 | //~ or 'const v: myLib.VetID = "bob";'
59 | type VetID = string | number;
60 |
61 | //~ We can invoke 'myLib.checkCat(c)' or 'myLib.checkCat(c, v);'
62 | function checkCat(c: Cat, s?: VetID);
63 | }
64 | ```
--------------------------------------------------------------------------------
/pages/declaration files/templates/module-function.d.ts.md:
--------------------------------------------------------------------------------
1 | ```ts
2 | // Type definitions for [~THE LIBRARY NAME~] [~OPTIONAL VERSION NUMBER~]
3 | // Project: [~THE PROJECT NAME~]
4 | // Definitions by: [~YOUR NAME~] <[~A URL FOR YOU~]>
5 |
6 | /*~ This is the module template file for function modules.
7 | *~ You should rename it to index.d.ts and place it in a folder with the same name as the module.
8 | *~ For example, if you were writing a file for "super-greeter", this
9 | *~ file should be 'super-greeter/index.d.ts'
10 | */
11 |
12 | /*~ Note that ES6 modules cannot directly export callable functions.
13 | *~ This file should be imported using the CommonJS-style:
14 | *~ import x = require('someLibrary');
15 | *~
16 | *~ Refer to the documentation to understand common
17 | *~ workarounds for this limitation of ES6 modules.
18 | */
19 |
20 | /*~ If this module is a UMD module that exposes a global variable 'myFuncLib' when
21 | *~ loaded outside a module loader environment, declare that global here.
22 | *~ Otherwise, delete this declaration.
23 | */
24 | export as namespace myFuncLib;
25 |
26 | /*~ This declaration specifies that the function
27 | *~ is the exported object from the file
28 | */
29 | export = MyFunction;
30 |
31 | /*~ This example shows how to have multiple overloads for your function */
32 | declare function MyFunction(name: string): MyFunction.NamedReturnType;
33 | declare function MyFunction(length: number): MyFunction.LengthReturnType;
34 |
35 | /*~ If you want to expose types from your module as well, you can
36 | *~ place them in this block. Often you will want to describe the
37 | *~ shape of the return type of the function; that type should
38 | *~ be declared in here, as this example shows.
39 | */
40 | declare namespace MyFunction {
41 | export interface LengthReturnType {
42 | width: number;
43 | height: number;
44 | }
45 | export interface NamedReturnType {
46 | firstName: string;
47 | lastName: string;
48 | }
49 |
50 | /*~ If the module also has properties, declare them here. For example,
51 | *~ this declaration says that this code is legal:
52 | *~ import f = require('myFuncLibrary');
53 | *~ console.log(f.defaultName);
54 | */
55 | export const defaultName: string;
56 | export let defaultLength: number;
57 | }
58 | ```
--------------------------------------------------------------------------------
/pages/declaration files/Introduction.md:
--------------------------------------------------------------------------------
1 | This guide is designed to teach you how to write a high-quality TypeScript Declaration File.
2 |
3 | In this guide, we'll assume basic familiarity with the TypeScript language.
4 | If you haven't already, you should read the [TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/basic-types.html)
5 | to familiarize yourself with basic concepts, especially types and namespaces.
6 |
7 | # Sections
8 |
9 | The guide is broken down into the following sections.
10 |
11 | ## Library Structures
12 |
13 | The [Library Structures](./Library Structures.md) guide helps you understand common library formats and how to write a correct declaration file for each format.
14 | If you're editing an existing file, you probably don't need to read this section.
15 | Authors of new declaration files must read this section to properly understand how the format of the library influences the writing of the declaration file.
16 |
17 | ## "Do"s and "Don't"s
18 |
19 | Many common mistakes in declaration files can be easily avoided.
20 | The [Do's and Don'ts](./Do's and Don'ts.md) section identifies common errors,
21 | describes how to detect them,
22 | and how to fix them.
23 | Everyone should read this section to help themselves avoid common mistakes.
24 |
25 | ## By Example
26 |
27 | Many times, we are faced with writing a declaration file when we only have examples of the underlying library to guide us.
28 | The [By Example](./By Example.md) section shows many common API patterns and how to write declarations for each of them.
29 | This guide is aimed at the TypeScript novice who may not yet be familiar with every language construct in TypeScript.
30 |
31 | ## Deep Dive
32 |
33 | For seasoned authors interested in the underlying mechanics of how declaration files work,
34 | the [Deep Dive](./Deep Dive.md) section explains many advanced concepts in declaration writing,
35 | and shows how to leverage these concepts to create cleaner and more intuitive declaration files.
36 |
37 | ## Templates
38 |
39 | In [Templates](./Templates.md) you'll find a number of declaration files that serve as a useful starting point
40 | when writing a new file.
41 | Refer to the documentation in [Library Structures](./Library Structures.md) to figure out which template file to use.
42 |
43 | ## Publish to npm
44 |
45 | The [Publishing](./Publishing.md) section explains how to publish your declaration files to an npm package, and shows how to manage your dependent packages.
46 |
47 | ## Find and Install Declaration Files
48 |
49 | For JavaScript library users, the [Consumption](./Consumption.md) section offers a few simple steps to locate and install corresponding declaration files.
50 |
--------------------------------------------------------------------------------
/pages/release notes/TypeScript 2.5.md:
--------------------------------------------------------------------------------
1 | # Optional `catch` clause variables
2 |
3 | Thanks to work done by [@tinganho](https://github.com/tinganho), TypeScript 2.5 implements a new ECMAScript feature that allows users to omit the variable in `catch` clauses.
4 | For example, when using `JSON.parse` you may need to wrap calls to the function with a `try`/`catch`, but you may not end up using the `SyntaxError` that gets thrown when input is erroneous.
5 |
6 | ```ts
7 | let input = "...";
8 | try {
9 | JSON.parse(input);
10 | }
11 | catch {
12 | // ^ Notice that our `catch` clause doesn't declare a variable.
13 | console.log("Invalid JSON given\n\n" + input)
14 | }
15 | ```
16 |
17 | # Type assertion/cast syntax in `checkJs`/`@ts-check` mode
18 |
19 | TypeScript 2.5 introduces the ability to [assert the type of expressions when using plain JavaScript in your projects](https://github.com/Microsoft/TypeScript/issues/5158).
20 | The syntax is an `/** @type {...} */` annotation comment followed by a parenthesized expression whose type needs to be re-evaluated.
21 | For example:
22 |
23 | ```ts
24 | var x = /** @type {SomeType} */ (AnyParenthesizedExpression);
25 | ```
26 |
27 | # Deduplicated and redirected packages
28 |
29 | When importing using the `Node` module resolution strategy in TypeScript 2.5, the compiler will now check whether files originate from "identical" packages.
30 | If a file originates from a package with a `package.json` containing the same `name` and `version` fields as a previously encountered package, then TypeScript will redirect itself to the top-most package.
31 | This helps resolve problems where two packages might contain identical declarations of classes, but which contain `private` members that cause them to be structurally incompatible.
32 |
33 | As a nice bonus, this can also reduce the memory and runtime footprint of the compiler and language service by avoiding loading `.d.ts` files from duplicate packages.
34 |
35 | # The `--preserveSymlinks` compiler flag
36 |
37 | TypeScript 2.5 brings the `preserveSymlinks` flag, which parallels the behavior of [the `--preserve-symlinks` flag in Node.js](https://nodejs.org/api/cli.html#cli_preserve_symlinks).
38 | This flag also exhibits the opposite behavior to Webpack's `resolve.symlinks` option (i.e. setting TypeScript's `preserveSymlinks` to `true` parallels setting Webpack's `resolve.symlinks` to `false`, and vice-versa).
39 |
40 | In this mode, references to modules and packages (e.g. `import`s and `/// ` directives) are all resolved relative to the location of the symbolic link file, rather than relative to the path that the symbolic link resolves to.
41 | For a more concrete example, we'll defer to [the documentation on the Node.js website](https://nodejs.org/api/cli.html#cli_preserve_symlinks).
42 |
--------------------------------------------------------------------------------
/pages/Iterators and Generators.md:
--------------------------------------------------------------------------------
1 | # Iterables
2 |
3 | An object is deemed iterable if it has an implementation for the [`Symbol.iterator`](Symbols.md#symboliterator) property.
4 | Some built-in types like `Array`, `Map`, `Set`, `String`, `Int32Array`, `Uint32Array`, etc. have their `Symbol.iterator` property already implemented.
5 | `Symbol.iterator` function on an object is responsible for returning the list of values to iterate on.
6 |
7 | ## `for..of` statements
8 |
9 | `for..of` loops over an iterable object, invoking the `Symbol.iterator` property on the object.
10 | Here is a simple `for..of` loop on an array:
11 |
12 | ```ts
13 | let someArray = [1, "string", false];
14 |
15 | for (let entry of someArray) {
16 | console.log(entry); // 1, "string", false
17 | }
18 | ```
19 |
20 | ### `for..of` vs. `for..in` statements
21 |
22 | Both `for..of` and `for..in` statements iterate over lists; the values iterated on are different though, `for..in` returns a list of *keys* on the object being iterated, whereas `for..of` returns a list of *values* of the numeric properties of the object being iterated.
23 |
24 | Here is an example that demonstrates this distinction:
25 |
26 | ```ts
27 | let list = [4, 5, 6];
28 |
29 | for (let i in list) {
30 | console.log(i); // "0", "1", "2",
31 | }
32 |
33 | for (let i of list) {
34 | console.log(i); // "4", "5", "6"
35 | }
36 | ```
37 |
38 | Another distinction is that `for..in` operates on any object; it serves as a way to inspect properties on this object.
39 | `for..of` on the other hand, is mainly interested in values of iterable objects. Built-in objects like `Map` and `Set` implement `Symbol.iterator` property allowing access to stored values.
40 |
41 | ```ts
42 | let pets = new Set(["Cat", "Dog", "Hamster"]);
43 | pets["species"] = "mammals";
44 |
45 | for (let pet in pets) {
46 | console.log(pet); // "species"
47 | }
48 |
49 | for (let pet of pets) {
50 | console.log(pet); // "Cat", "Dog", "Hamster"
51 | }
52 | ```
53 |
54 | ### Code generation
55 |
56 | #### Targeting ES5 and ES3
57 |
58 | When targeting an ES5 or ES3, iterators are only allowed on values of `Array` type.
59 | It is an error to use `for..of` loops on non-Array values, even if these non-Array values implement the `Symbol.iterator` property.
60 |
61 | The compiler will generate a simple `for` loop for a `for..of` loop, for instance:
62 |
63 | ```ts
64 | let numbers = [1, 2, 3];
65 | for (let num of numbers) {
66 | console.log(num);
67 | }
68 | ```
69 |
70 | will be generated as:
71 |
72 | ```js
73 | var numbers = [1, 2, 3];
74 | for (var _i = 0; _i < numbers.length; _i++) {
75 | var num = numbers[_i];
76 | console.log(num);
77 | }
78 | ```
79 |
80 | #### Targeting ECMAScript 2015 and higher
81 |
82 | When targeting an ECMAScipt 2015-compliant engine, the compiler will generate `for..of` loops to target the built-in iterator implementation in the engine.
83 |
--------------------------------------------------------------------------------
/pages/Nightly Builds.md:
--------------------------------------------------------------------------------
1 | A nightly build from the [TypeScript's `master`](https://github.com/Microsoft/TypeScript/tree/master) branch is published by midnight PST to NPM and NuGet.
2 | Here is how you can get it and use it with your tools.
3 |
4 | ## Using npm
5 |
6 | ```shell
7 | npm install -g typescript@next
8 | ```
9 |
10 | ## Using NuGet with MSBuild
11 |
12 | > Note: You'll need to configure your project to use the NuGet packages.
13 | Please see [Configuring MSBuild projects to use NuGet](https://github.com/Microsoft/TypeScript/wiki/Configuring-MSBuild-projects-to-use-NuGet) for more information.
14 |
15 | The nightlies are available on [www.myget.org](https://www.myget.org/gallery/typescript-preview).
16 |
17 | There are two packages:
18 |
19 | * `Microsoft.TypeScript.Compiler`: Tools only (`tsc.exe`, `lib.d.ts`, etc.) .
20 | * `Microsoft.TypeScript.MSBuild`: Tools as above, as well as MSBuild tasks and targets (`Microsoft.TypeScript.targets`, `Microsoft.TypeScript.Default.props`, etc.)
21 |
22 | ## Updating your IDE to use the nightly builds
23 |
24 | You can also update your IDE to use the nightly drop.
25 | First you will need to install the package through npm.
26 | You can either install the npm package globally or to a local `node_modules` folder.
27 |
28 | The rest of this section assumes `typescript@next` is already installed.
29 |
30 | ### Visual Studio Code
31 |
32 | Update `.vscode/settings.json` with the following:
33 |
34 | ```json
35 | "typescript.tsdk": "/node_modules/typescript/lib"
36 | ```
37 |
38 | More information is available at [VSCode documentation](https://code.visualstudio.com/Docs/languages/typescript#_using-newer-typescript-versions).
39 |
40 | ### Sublime Text
41 |
42 | Update the `Settings - User` file with the following:
43 |
44 | ```json
45 | "typescript_tsdk": "/node_modules/typescript/lib"
46 | ```
47 |
48 | More information is available at the [TypeScript Plugin for Sublime Text installation documentation](https://github.com/Microsoft/TypeScript-Sublime-Plugin#installation).
49 |
50 | ### Visual Studio 2013 and 2015
51 |
52 | > Note: Most changes do not require you to install a new version of the VS TypeScript plugin.
53 |
54 | The nightly build currently does not include the full plugin setup, but we are working on publishing an installer on a nightly basis as well.
55 |
56 | 1. Download the [VSDevMode.ps1](https://github.com/Microsoft/TypeScript/blob/master/scripts/VSDevMode.ps1) script.
57 |
58 | > Also see our wiki page on [using a custom language service file](https://github.com/Microsoft/TypeScript/wiki/Dev-Mode-in-Visual-Studio#using-a-custom-language-service-file).
59 |
60 | 2. From a PowerShell command window, run:
61 |
62 | For VS 2015:
63 |
64 | ```posh
65 | VSDevMode.ps1 14 -tsScript /node_modules/typescript/lib
66 | ```
67 |
68 | For VS 2013:
69 |
70 | ```posh
71 | VSDevMode.ps1 12 -tsScript /node_modules/typescript/lib
72 | ```
73 |
74 | ### IntelliJ IDEA (Mac)
75 |
76 | Go to `Preferences` > `Languages & Frameworks` > `TypeScript`:
77 | > TypeScript Version: If you installed with npm: `/usr/local/lib/node_modules/typescript/lib`
78 |
--------------------------------------------------------------------------------
/pages/Symbols.md:
--------------------------------------------------------------------------------
1 | # Introduction
2 |
3 | Starting with ECMAScript 2015, `symbol` is a primitive data type, just like `number` and `string`.
4 |
5 | `symbol` values are created by calling the `Symbol` constructor.
6 |
7 | ```ts
8 | let sym1 = Symbol();
9 |
10 | let sym2 = Symbol("key"); // optional string key
11 | ```
12 |
13 | Symbols are immutable, and unique.
14 |
15 | ```ts
16 | let sym2 = Symbol("key");
17 | let sym3 = Symbol("key");
18 |
19 | sym2 === sym3; // false, symbols are unique
20 | ```
21 |
22 | Just like strings, symbols can be used as keys for object properties.
23 |
24 | ```ts
25 | let sym = Symbol();
26 |
27 | let obj = {
28 | [sym]: "value"
29 | };
30 |
31 | console.log(obj[sym]); // "value"
32 | ```
33 |
34 | Symbols can also be combined with computed property declarations to declare object properties and class members.
35 |
36 | ```ts
37 | const getClassNameSymbol = Symbol();
38 |
39 | class C {
40 | [getClassNameSymbol](){
41 | return "C";
42 | }
43 | }
44 |
45 | let c = new C();
46 | let className = c[getClassNameSymbol](); // "C"
47 | ```
48 |
49 | # Well-known Symbols
50 |
51 | In addition to user-defined symbols, there are well-known built-in symbols.
52 | Built-in symbols are used to represent internal language behaviors.
53 |
54 | Here is a list of well-known symbols:
55 |
56 | ## `Symbol.hasInstance`
57 |
58 | A method that determines if a constructor object recognizes an object as one of the constructor’s instances. Called by the semantics of the instanceof operator.
59 |
60 | ## `Symbol.isConcatSpreadable`
61 |
62 | A Boolean value indicating that an object should be flatten to its array elements by Array.prototype.concat.
63 |
64 | ## `Symbol.iterator`
65 |
66 | A method that returns the default iterator for an object. Called by the semantics of the for-of statement.
67 |
68 | ## `Symbol.match`
69 |
70 | A regular expression method that matches the regular expression against a string. Called by the `String.prototype.match` method.
71 |
72 | ## `Symbol.replace`
73 |
74 | A regular expression method that replaces matched substrings of a string. Called by the `String.prototype.replace` method.
75 |
76 | ## `Symbol.search`
77 |
78 | A regular expression method that returns the index within a string that matches the regular expression. Called by the `String.prototype.search` method.
79 |
80 | ## `Symbol.species`
81 |
82 | A function valued property that is the constructor function that is used to create derived objects.
83 |
84 | ## `Symbol.split`
85 |
86 | A regular expression method that splits a string at the indices that match the regular expression.
87 | Called by the `String.prototype.split` method.
88 |
89 | ## `Symbol.toPrimitive`
90 |
91 | A method that converts an object to a corresponding primitive value.
92 | Called by the `ToPrimitive` abstract operation.
93 |
94 | ## `Symbol.toStringTag`
95 |
96 | A String value that is used in the creation of the default string description of an object.
97 | Called by the built-in method `Object.prototype.toString`.
98 |
99 | ## `Symbol.unscopables`
100 |
101 | An Object whose own property names are property names that are excluded from the 'with' environment bindings of the associated objects.
102 |
--------------------------------------------------------------------------------
/pages/Type Inference.md:
--------------------------------------------------------------------------------
1 | # Introduction
2 |
3 | In this section, we will cover type inference in TypeScript. Namely, we'll discuss where and how types are inferred.
4 |
5 | # Basics
6 |
7 | In TypeScript, there are several places where type inference is used to provide type information when there is no explicit type annotation. For example, in this code
8 |
9 | ```ts
10 | let x = 3;
11 | ```
12 |
13 | The type of the `x` variable is inferred to be `number`.
14 | This kind of inference takes place when initializing variables and members, setting parameter default values, and determining function return types.
15 |
16 | In most cases, type inference is straightforward.
17 | In the following sections, we'll explore some of the nuances in how types are inferred.
18 |
19 | # Best common type
20 |
21 | When a type inference is made from several expressions, the types of those expressions are used to calculate a "best common type". For example,
22 |
23 | ```ts
24 | let x = [0, 1, null];
25 | ```
26 |
27 | To infer the type of `x` in the example above, we must consider the type of each array element.
28 | Here we are given two choices for the type of the array: `number` and `null`.
29 | The best common type algorithm considers each candidate type, and picks the type that is compatible with all the other candidates.
30 |
31 | Because the best common type has to be chosen from the provided candidate types, there are some cases where types share a common structure, but no one type is the super type of all candidate types. For example:
32 |
33 | ```ts
34 | let zoo = [new Rhino(), new Elephant(), new Snake()];
35 | ```
36 |
37 | Ideally, we may want `zoo` to be inferred as an `Animal[]`, but because there is no object that is strictly of type `Animal` in the array, we make no inference about the array element type.
38 | To correct this, instead explicitly provide the type when no one type is a super type of all other candidates:
39 |
40 | ```ts
41 | let zoo: Animal[] = [new Rhino(), new Elephant(), new Snake()];
42 | ```
43 |
44 | When no best common type is found, the resulting inference is the union array type, `(Rhino | Elephant | Snake)[]`.
45 |
46 | # Contextual Type
47 |
48 | Type inference also works in "the other direction" in some cases in TypeScript.
49 | This is known as "contextual typing". Contextual typing occurs when the type of an expression is implied by its location. For example:
50 |
51 | ```ts
52 | window.onmousedown = function(mouseEvent) {
53 | console.log(mouseEvent.button); //<- Error
54 | };
55 | ```
56 |
57 | For the code above to give the type error, the TypeScript type checker used the type of the `Window.onmousedown` function to infer the type of the function expression on the right hand side of the assignment.
58 | When it did so, it was able to infer the type of the `mouseEvent` parameter.
59 | If this function expression were not in a contextually typed position, the `mouseEvent` parameter would have type `any`, and no error would have been issued.
60 |
61 | If the contextually typed expression contains explicit type information, the contextual type is ignored.
62 | Had we written the above example:
63 |
64 | ```ts
65 | window.onmousedown = function(mouseEvent: any) {
66 | console.log(mouseEvent.button); //<- Now, no error is given
67 | };
68 | ```
69 |
70 | The function expression with an explicit type annotation on the parameter will override the contextual type.
71 | Once it does so, no error is given as no contextual type applies.
72 |
73 | Contextual typing applies in many cases.
74 | Common cases include arguments to function calls, right hand sides of assignments, type assertions, members of object and array literals, and return statements.
75 | The contextual type also acts as a candidate type in best common type. For example:
76 |
77 | ```ts
78 | function createZoo(): Animal[] {
79 | return [new Rhino(), new Elephant(), new Snake()];
80 | }
81 | ```
82 |
83 | In this example, best common type has a set of four candidates: `Animal`, `Rhino`, `Elephant`, and `Snake`.
84 | Of these, `Animal` can be chosen by the best common type algorithm.
85 |
--------------------------------------------------------------------------------
/pages/declaration files/Publishing.md:
--------------------------------------------------------------------------------
1 | Now that you have authored a declaration file following the steps of this guide, it is time to publish it to npm.
2 | There are two main ways you can publish your declaration files to npm:
3 |
4 | 1. bundling with your npm package, or
5 | 2. publishing to the [@types organization](https://www.npmjs.com/~types) on npm.
6 |
7 | If you control the npm package you are publishing declarations for, then the first approach is favored.
8 | That way, your declarations and JavaScript always travel together.
9 |
10 | # Including declarations in your npm package
11 |
12 | If your package has a main `.js` file, you will need to indicate the main declaration file in your `package.json` file as well.
13 | Set the `types` property to point to your bundled declaration file.
14 | For example:
15 |
16 | ```json
17 | {
18 | "name": "awesome",
19 | "author": "Vandelay Industries",
20 | "version": "1.0.0",
21 | "main": "./lib/main.js",
22 | "types": "./lib/main.d.ts"
23 | }
24 | ```
25 |
26 | Note that the `"typings"` field is synonymous with `"types"`, and could be used as well.
27 |
28 | Also note that if your main declaration file is named `index.d.ts` and lives at the root of the package (next to `index.js`) you do not need to mark the `"types"` property, though it is advisable to do so.
29 |
30 | ## Dependencies
31 |
32 | All dependencies are managed by npm.
33 | Make sure all the declaration packages you depend on are marked appropriately in the `"dependencies"` section in your `package.json`.
34 | For example, imagine we authored a package that used Browserify and TypeScript.
35 |
36 | ```json
37 | {
38 | "name": "browserify-typescript-extension",
39 | "author": "Vandelay Industries",
40 | "version": "1.0.0",
41 | "main": "./lib/main.js",
42 | "types": "./lib/main.d.ts",
43 | "dependencies": {
44 | "browserify": "latest",
45 | "@types/browserify": "latest",
46 | "typescript": "next"
47 | }
48 | }
49 | ```
50 |
51 | Here, our package depends on the `browserify` and `typescript` packages.
52 | `browserify` does not bundle its declaration files with its npm packages, so we needed to depend on `@types/browserify` for its declarations.
53 | `typescript`, on the other hand, packages its declaration files, so there was no need for any additional dependencies
54 |
55 | Our package exposes declarations from each of those, so any user of our `browserify-typescript-extension` package needs to have these dependencies as well.
56 | For that reason, we used `"dependencies"` and not `"devDependencies"`, because otherwise our consumers would have needed to manually install those packages.
57 | If we had just written a command line application and not expected our package to be used as a library, we might have used `devDependencies`.
58 |
59 | ## Red flags
60 |
61 | ### `/// `
62 |
63 | *Don't* use `/// ` in your declaration files.
64 |
65 | ```ts
66 | ///
67 | ....
68 | ```
69 |
70 | *Do* use `/// ` instead.
71 |
72 | ```ts
73 | ///
74 | ....
75 | ```
76 |
77 | Make sure to revisit the [Consuming dependencies](./Library Structures.md#consuming-dependencies) section for more information.
78 |
79 | ### Packaging dependent declarations
80 |
81 | If your type definitions depend on another package:
82 |
83 | * *Don't* combine it with yours, keep each in their own file.
84 | * *Don't* copy the declarations in your package either.
85 | * *Do* depend on the npm type declaration package if it doesn't package its declaration files.
86 |
87 | # Publish to [@types](https://www.npmjs.com/~types)
88 |
89 | Packages on under the [@types](https://www.npmjs.com/~types) organization are published automatically from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) using the [types-publisher tool](https://github.com/Microsoft/types-publisher).
90 | To get your declarations published as an @types package, please submit a pull request to [https://github.com/DefinitelyTyped/DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped).
91 | You can find more details in the [contribution guidelines page](http://definitelytyped.org/guides/contributing.html).
92 |
--------------------------------------------------------------------------------
/pages/Mixins.md:
--------------------------------------------------------------------------------
1 | # Introduction
2 |
3 | Along with traditional OO hierarchies, another popular way of building up classes from reusable components is to build them by combining simpler partial classes.
4 | You may be familiar with the idea of mixins or traits for languages like Scala, and the pattern has also reached some popularity in the JavaScript community.
5 |
6 | # Mixin sample
7 |
8 | In the code below, we show how you can model mixins in TypeScript.
9 | After the code, we'll break down how it works.
10 |
11 | ```ts
12 | // Disposable Mixin
13 | class Disposable {
14 | isDisposed: boolean;
15 | dispose() {
16 | this.isDisposed = true;
17 | }
18 |
19 | }
20 |
21 | // Activatable Mixin
22 | class Activatable {
23 | isActive: boolean;
24 | activate() {
25 | this.isActive = true;
26 | }
27 | deactivate() {
28 | this.isActive = false;
29 | }
30 | }
31 |
32 | class SmartObject implements Disposable, Activatable {
33 | constructor() {
34 | setInterval(() => console.log(this.isActive + " : " + this.isDisposed), 500);
35 | }
36 |
37 | interact() {
38 | this.activate();
39 | }
40 |
41 | // Disposable
42 | isDisposed: boolean = false;
43 | dispose: () => void;
44 | // Activatable
45 | isActive: boolean = false;
46 | activate: () => void;
47 | deactivate: () => void;
48 | }
49 | applyMixins(SmartObject, [Disposable, Activatable]);
50 |
51 | let smartObj = new SmartObject();
52 | setTimeout(() => smartObj.interact(), 1000);
53 |
54 | ////////////////////////////////////////
55 | // In your runtime library somewhere
56 | ////////////////////////////////////////
57 |
58 | function applyMixins(derivedCtor: any, baseCtors: any[]) {
59 | baseCtors.forEach(baseCtor => {
60 | Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
61 | derivedCtor.prototype[name] = baseCtor.prototype[name];
62 | });
63 | });
64 | }
65 | ```
66 |
67 | # Understanding the sample
68 |
69 | The code sample starts with the two classes that will act as our mixins.
70 | You can see each one is focused on a particular activity or capability.
71 | We'll later mix these together to form a new class from both capabilities.
72 |
73 | ```ts
74 | // Disposable Mixin
75 | class Disposable {
76 | isDisposed: boolean;
77 | dispose() {
78 | this.isDisposed = true;
79 | }
80 |
81 | }
82 |
83 | // Activatable Mixin
84 | class Activatable {
85 | isActive: boolean;
86 | activate() {
87 | this.isActive = true;
88 | }
89 | deactivate() {
90 | this.isActive = false;
91 | }
92 | }
93 | ```
94 |
95 | Next, we'll create the class that will handle the combination of the two mixins.
96 | Let's look at this in more detail to see how it does this:
97 |
98 | ```ts
99 | class SmartObject implements Disposable, Activatable {
100 | ```
101 |
102 | The first thing you may notice in the above is that instead of using `extends`, we use `implements`.
103 | This treats the classes as interfaces, and only uses the types behind Disposable and Activatable rather than the implementation.
104 | This means that we'll have to provide the implementation in class.
105 | Except, that's exactly what we want to avoid by using mixins.
106 |
107 | To satisfy this requirement, we create stand-in properties and their types for the members that will come from our mixins.
108 | This satisfies the compiler that these members will be available at runtime.
109 | This lets us still get the benefit of the mixins, albeit with some bookkeeping overhead.
110 |
111 | ```ts
112 | // Disposable
113 | isDisposed: boolean = false;
114 | dispose: () => void;
115 | // Activatable
116 | isActive: boolean = false;
117 | activate: () => void;
118 | deactivate: () => void;
119 | ```
120 |
121 | Finally, we mix our mixins into the class, creating the full implementation.
122 |
123 | ```ts
124 | applyMixins(SmartObject, [Disposable, Activatable]);
125 | ```
126 |
127 | Lastly, we create a helper function that will do the mixing for us.
128 | This will run through the properties of each of the mixins and copy them over to the target of the mixins, filling out the stand-in properties with their implementations.
129 |
130 | ```ts
131 | function applyMixins(derivedCtor: any, baseCtors: any[]) {
132 | baseCtors.forEach(baseCtor => {
133 | Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
134 | derivedCtor.prototype[name] = baseCtor.prototype[name];
135 | });
136 | });
137 | }
138 |
139 | ```
140 |
--------------------------------------------------------------------------------
/lint.js:
--------------------------------------------------------------------------------
1 | var markdownlint = require("markdownlint");
2 | var glob = require("glob");
3 | var fs = require("fs");
4 |
5 | var inputFiles = glob.sync("**/*.md", { ignore: "node_modules/**/*" });
6 | var options = {
7 | files: inputFiles,
8 | config: {
9 | MD001: false, // Header levels should only increment by one level at a time
10 | MD002: false, // First header should be a h1 header
11 | MD003: "atx", // Header style
12 | MD004: { style: "asterisk" }, // Unordered list style
13 | MD005: true, // Inconsistent indentation for list items at the same level
14 | MD006: true, // Consider starting bulleted lists at the beginning of the line
15 | MD007: { indent: 4 }, // Unordered list indentation
16 | MD009: true, // Trailing spaces
17 | MD010: true, // Hard tabs
18 | MD011: true, // Reversed link syntax
19 | MD012: true, // Multiple consecutive blank lines
20 | MD013: false, // Line length
21 | MD014: false, // Dollar signs used before commands without showing output
22 | MD018: true, // No space after hash on atx style header
23 | MD019: true, // Multiple spaces after hash on atx style header
24 | MD020: false, // No space inside hashes on closed atx style header
25 | MD021: false, // Multiple spaces inside hashes on closed atx style header
26 | MD022: true, // Headers should be surrounded by blank lines
27 | MD023: true, // Headers must start at the beginning of the line
28 | MD024: false, // Multiple headers with the same content
29 | MD025: false, // Multiple top level headers in the same document
30 | MD026: { punctuation: ".,;:!" }, // Trailing punctuation in header
31 | MD027: true, // Multiple spaces after blockquote symbol
32 | MD028: true, // Blank line inside blockquote
33 | MD029: { style: "ordered" }, // Ordered list item prefix
34 | MD030: true, // Spaces after list markers
35 | MD031: true, // Fenced code blocks should be surrounded by blank lines
36 | MD032: true, // Lists should be surrounded by blank lines
37 | MD033: false, // Inline HTML
38 | MD034: true, // Bare URL used
39 | MD035: "---", // Horizontal rule style
40 | MD036: false, // Emphasis used instead of a header
41 | MD037: true, // Spaces inside emphasis markers
42 | MD038: false, // Spaces inside code span elements
43 | MD039: true, // Spaces inside link text
44 | MD040: true, // Fenced code blocks should have a language specified
45 | MD041: false, // First line in file should be a top level header
46 | }
47 | };
48 |
49 | var result = markdownlint.sync(options);
50 | console.log(result.toString());
51 |
52 | var exitCode = 0;
53 | Object.keys(result).forEach(function (file) {
54 | var fileResults = result[file];
55 | Object.keys(fileResults).forEach(function (rule) {
56 | var ruleResults = fileResults[rule];
57 | exitCode += ruleResults.length;
58 | });
59 | });
60 |
61 | inputFiles.forEach(function(fileName) {
62 | var text = fs.readFileSync(fileName, "utf8")
63 | exitCode += checkForImproperlyIndentedFencedCodeBlocks(fileName, text);
64 | })
65 |
66 | process.exit(exitCode);
67 |
68 | /**
69 | * @param {string} fileName
70 | * @param {string} text
71 | */
72 | function checkForImproperlyIndentedFencedCodeBlocks(fileName, text) {
73 | var lines = text.split(/\r?\n/g);
74 | var numErrors = 0;
75 |
76 | for (var i = 0; i < lines.length; i++) {
77 | var line = lines[i];
78 | var codeBlockMatch = line.match(/^(\s*)```\S+/);
79 |
80 | if (codeBlockMatch) {
81 | var startingColumn = codeBlockMatch[1].length;
82 | if (startingColumn === 0 || startingColumn === getCorrectStartingColumnForLine(lines, i)) {
83 | continue;
84 | }
85 |
86 | numErrors++;
87 | console.log(fileName + ": " +
88 | i + 1 + ": A fenced code block following a list item must be indented to the first non-whitespace character of the list item.")
89 | }
90 | }
91 |
92 | return numErrors;
93 | }
94 |
95 | /**
96 | * @param {string[]} line
97 | * @param {number} lineIndex
98 | */
99 | function getCorrectStartingColumnForLine(lines, lineIndex) {
100 | for (var i = lineIndex - 1; i >= 0; i--) {
101 | var line = lines[i];
102 |
103 | if (line.length === 0) {
104 | continue;
105 | }
106 |
107 | var m;
108 | if (m = line.match(/^\s*([\*\-]|(\d+\.))\s*/)) {
109 | return m[0].length;
110 | }
111 | if (m = line.match(/^(\s*)/)) {
112 | return m[0].length;
113 | }
114 | }
115 |
116 | return 0;
117 | }
--------------------------------------------------------------------------------
/pages/Triple-Slash Directives.md:
--------------------------------------------------------------------------------
1 | Triple-slash directives are single-line comments containing a single XML tag.
2 | The contents of the comment are used as compiler directives.
3 |
4 | Triple-slash directives are **only** valid at the top of their containing file.
5 | A triple-slash directive can only be preceded by single or multi-line comments, including other triple-slash directives.
6 | If they are encountered following a statement or a declaration they are treated as regular single-line comments, and hold no special meaning.
7 |
8 | ## `/// `
9 |
10 | The `/// ` directive is the most common of this group.
11 | It serves as a declaration of *dependency* between files.
12 |
13 | Triple-slash references instruct the compiler to include additional files in the compilation process.
14 |
15 | They also serve as a method to order the output when using `--out` or `--outFile`.
16 | Files are emitted to the output file location in the same order as the input after preprocessing pass.
17 |
18 | ### Preprocessing input files
19 |
20 | The compiler performs a preprocessing pass on input files to resolve all triple-slash reference directives.
21 | During this process, additional files are added to the compilation.
22 |
23 | The process starts with a set of *root files*;
24 | these are the file names specified on the command-line or in the `"files"` list in the `tsconfig.json` file.
25 | These root files are preprocessed in the same order they are specified.
26 | Before a file is added to the list, all triple-slash references in it are processed, and their targets included.
27 | Triple-slash references are resolved in a depth first manner, in the order they have been seen in the file.
28 |
29 | A triple-slash reference path is resolved relative to the containing file, if unrooted.
30 |
31 | ### Errors
32 |
33 | It is an error to reference a file that does not exist.
34 | It is an error for a file to have a triple-slash reference to itself.
35 |
36 | ### Using `--noResolve`
37 |
38 | If the compiler flag `--noResolve` is specified, triple-slash references are ignored; they neither result in adding new files, nor change the order of the files provided.
39 |
40 | ## `/// `
41 |
42 | Similar to a `/// ` directive, this directive serves as a declaration of *dependency*;
43 | a `/// ` directive, however, declares a dependency on a package.
44 |
45 | The process of resolving these package names is similar to the process of resolving module names in an `import` statement.
46 | An easy way to think of triple-slash-reference-types directives are as an `import` for declaration packages.
47 |
48 | For example, including `/// ` in a declaration file declares that this file uses names declared in `@types/node/index.d.ts`;
49 | and thus, this package needs to be included in the compilation along with the declaration file.
50 |
51 | Use these directives only when you're authoring a `d.ts` file by hand.
52 |
53 | For declaration files generated during compilation, the compiler will automatically add `/// ` for you;
54 | A `/// ` in a generated declaration file is added *if and only if* the resulting file uses any declarations from the referenced package.
55 |
56 | For declaring a dependency on an `@types` package in a `.ts` file, use `--types` on the command line or in your `tsconfig.json` instead.
57 | See [using `@types`, `typeRoots` and `types` in `tsconfig.json` files](./tsconfig.json.md#types-typeroots-and-types) for more details.
58 |
59 | ## `/// `
60 |
61 | This directive marks a file as a *default library*.
62 | You will see this comment at the top of `lib.d.ts` and its different variants.
63 |
64 | This directive instructs the compiler to *not* include the default library (i.e. `lib.d.ts`) in the compilation.
65 | The impact here is similar to passing `--noLib` on the command line.
66 |
67 | Also note that when passing `--skipDefaultLibCheck`, the compiler will only skip checking files with `/// `.
68 |
69 | ## `/// `
70 |
71 | By default AMD modules are generated anonymous.
72 | This can lead to problems when other tools are used to process the resulting modules, such as bundlers (e.g. `r.js`).
73 |
74 | The `amd-module` directive allows passing an optional module name to the compiler:
75 |
76 | ##### amdModule.ts
77 |
78 | ```ts
79 | ///
80 | export class C {
81 | }
82 | ```
83 |
84 | Will result in assigning the name `NamedModule` to the module as part of calling the AMD `define`:
85 |
86 | ##### amdModule.js
87 |
88 | ```js
89 | define("NamedModule", ["require", "exports"], function (require, exports) {
90 | var C = (function () {
91 | function C() {
92 | }
93 | return C;
94 | })();
95 | exports.C = C;
96 | });
97 | ```
98 |
99 | ## `/// `
100 |
101 | > **Note**: this directive has been deprecated. Use `import "moduleName";` statements instead.
102 |
103 | `/// ` informs the compiler about a non-TS module dependency that needs to be injected in the resulting module's require call.
104 |
105 | The `amd-dependency` directive can also have an optional `name` property; this allows passing an optional name for an amd-dependency:
106 |
107 | ```ts
108 | ///
109 | declare var moduleA:MyType
110 | moduleA.callStuff()
111 | ```
112 |
113 | Generated JS code:
114 |
115 | ```js
116 | define(["require", "exports", "legacy/moduleA"], function (require, exports, moduleA) {
117 | moduleA.callStuff()
118 | });
119 | ```
120 |
--------------------------------------------------------------------------------
/pages/Namespaces and Modules.md:
--------------------------------------------------------------------------------
1 | > **A note about terminology:**
2 | It's important to note that in TypeScript 1.5, the nomenclature has changed.
3 | "Internal modules" are now "namespaces".
4 | "External modules" are now simply "modules", as to align with [ECMAScript 2015](http://www.ecma-international.org/ecma-262/6.0/)'s terminology, (namely that `module X {` is equivalent to the now-preferred `namespace X {`).
5 |
6 | # Introduction
7 |
8 | This post outlines the various ways to organize your code using namespaces and modules in TypeScript.
9 | We'll also go over some advanced topics of how to use namespaces and modules, and address some common pitfalls when using them in TypeScript.
10 |
11 | See the [Modules](./Modules.md) documentation for more information about modules.
12 | See the [Namespaces](./Namespaces.md) documentation for more information about namespaces.
13 |
14 | # Using Namespaces
15 |
16 | Namespaces are simply named JavaScript objects in the global namespace.
17 | This makes namespaces a very simple construct to use.
18 | They can span multiple files, and can be concatenated using `--outFile`.
19 | Namespaces can be a good way to structure your code in a Web Application, with all dependencies included as `
155 |