├── .gitattributes ├── .gitignore ├── .travis.yml ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── assets └── images │ └── tutorials │ └── aspnet │ ├── install-nuget-packages.png │ ├── new-asp-project-empty-17.PNG │ ├── new-asp-project-empty.png │ ├── new-asp-project.png │ ├── new-folder.png │ ├── new-item.png │ ├── new-tsconfig.png │ ├── open-index.png │ ├── packageinstaller-angular2.png │ ├── packageinstaller-es6-shim.png │ ├── packageinstaller-systemjs.png │ ├── packageinstaller-typings.png │ ├── paused-demo.png │ ├── running-demo.png │ ├── scripts-folder.png │ ├── src-folder.png │ └── task-runner-explorer.png ├── lint.js ├── package.json ├── pages ├── Advanced Types.md ├── Basic Types.md ├── Classes.md ├── Compiler Options in MSBuild.md ├── Compiler Options.md ├── Declaration Merging.md ├── Decorators.md ├── Enums.md ├── Functions.md ├── Generics.md ├── Integrating with Build Tools.md ├── Interfaces.md ├── Iterators and Generators.md ├── JSX.md ├── Mixins.md ├── Module Resolution.md ├── Modules.md ├── Namespaces and Modules.md ├── Namespaces.md ├── Nightly Builds.md ├── Symbols.md ├── Triple-Slash Directives.md ├── Type Checking JavaScript Files.md ├── Type Compatibility.md ├── Type Inference.md ├── Typings for NPM Packages.md ├── Variable Declarations.md ├── Writing Declaration Files.md ├── declaration files │ ├── By Example.md │ ├── Consumption.md │ ├── Deep Dive.md │ ├── Do's and Don'ts.md │ ├── Introduction.md │ ├── Library Structures.md │ ├── Publishing.md │ ├── Templates.md │ └── templates │ │ ├── global-modifying-module.d.ts.md │ │ ├── global-plugin.d.ts.md │ │ ├── global.d.ts.md │ │ ├── module-class.d.ts.md │ │ ├── module-function.d.ts.md │ │ ├── module-plugin.d.ts.md │ │ └── module.d.ts.md ├── release notes │ ├── TypeScript 1.1.md │ ├── TypeScript 1.3.md │ ├── TypeScript 1.4.md │ ├── TypeScript 1.5.md │ ├── TypeScript 1.6.md │ ├── TypeScript 1.7.md │ ├── TypeScript 1.8.md │ ├── TypeScript 2.0.md │ ├── TypeScript 2.1.md │ ├── TypeScript 2.2.md │ ├── TypeScript 2.3.md │ ├── TypeScript 2.4.md │ ├── TypeScript 2.5.md │ └── TypeScript 2.6.md ├── tsconfig.json.md └── tutorials │ ├── ASP.NET Core.md │ ├── Angular.md │ ├── Gulp.md │ ├── Migrating from JavaScript.md │ ├── React & Webpack.md │ ├── React.md │ └── TypeScript in 5 minutes.md └── pull_request_template.md /.gitattributes: -------------------------------------------------------------------------------- 1 | # Normalize line endings for all text files. 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .vscode -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "node" -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TypeScript-Handbook 2 | 3 | [![Build Status](https://travis-ci.org/Microsoft/TypeScript-Handbook.svg)](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 | -------------------------------------------------------------------------------- /assets/images/tutorials/aspnet/install-nuget-packages.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ry/TypeScript-Handbook/3eda844624d4bfc0a9506f194a8b9d139dc002b3/assets/images/tutorials/aspnet/install-nuget-packages.png -------------------------------------------------------------------------------- /assets/images/tutorials/aspnet/new-asp-project-empty-17.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ry/TypeScript-Handbook/3eda844624d4bfc0a9506f194a8b9d139dc002b3/assets/images/tutorials/aspnet/new-asp-project-empty-17.PNG -------------------------------------------------------------------------------- /assets/images/tutorials/aspnet/new-asp-project-empty.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ry/TypeScript-Handbook/3eda844624d4bfc0a9506f194a8b9d139dc002b3/assets/images/tutorials/aspnet/new-asp-project-empty.png -------------------------------------------------------------------------------- /assets/images/tutorials/aspnet/new-asp-project.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ry/TypeScript-Handbook/3eda844624d4bfc0a9506f194a8b9d139dc002b3/assets/images/tutorials/aspnet/new-asp-project.png -------------------------------------------------------------------------------- /assets/images/tutorials/aspnet/new-folder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ry/TypeScript-Handbook/3eda844624d4bfc0a9506f194a8b9d139dc002b3/assets/images/tutorials/aspnet/new-folder.png -------------------------------------------------------------------------------- /assets/images/tutorials/aspnet/new-item.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ry/TypeScript-Handbook/3eda844624d4bfc0a9506f194a8b9d139dc002b3/assets/images/tutorials/aspnet/new-item.png -------------------------------------------------------------------------------- /assets/images/tutorials/aspnet/new-tsconfig.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ry/TypeScript-Handbook/3eda844624d4bfc0a9506f194a8b9d139dc002b3/assets/images/tutorials/aspnet/new-tsconfig.png -------------------------------------------------------------------------------- /assets/images/tutorials/aspnet/open-index.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ry/TypeScript-Handbook/3eda844624d4bfc0a9506f194a8b9d139dc002b3/assets/images/tutorials/aspnet/open-index.png -------------------------------------------------------------------------------- /assets/images/tutorials/aspnet/packageinstaller-angular2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ry/TypeScript-Handbook/3eda844624d4bfc0a9506f194a8b9d139dc002b3/assets/images/tutorials/aspnet/packageinstaller-angular2.png -------------------------------------------------------------------------------- /assets/images/tutorials/aspnet/packageinstaller-es6-shim.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ry/TypeScript-Handbook/3eda844624d4bfc0a9506f194a8b9d139dc002b3/assets/images/tutorials/aspnet/packageinstaller-es6-shim.png -------------------------------------------------------------------------------- /assets/images/tutorials/aspnet/packageinstaller-systemjs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ry/TypeScript-Handbook/3eda844624d4bfc0a9506f194a8b9d139dc002b3/assets/images/tutorials/aspnet/packageinstaller-systemjs.png -------------------------------------------------------------------------------- /assets/images/tutorials/aspnet/packageinstaller-typings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ry/TypeScript-Handbook/3eda844624d4bfc0a9506f194a8b9d139dc002b3/assets/images/tutorials/aspnet/packageinstaller-typings.png -------------------------------------------------------------------------------- /assets/images/tutorials/aspnet/paused-demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ry/TypeScript-Handbook/3eda844624d4bfc0a9506f194a8b9d139dc002b3/assets/images/tutorials/aspnet/paused-demo.png -------------------------------------------------------------------------------- /assets/images/tutorials/aspnet/running-demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ry/TypeScript-Handbook/3eda844624d4bfc0a9506f194a8b9d139dc002b3/assets/images/tutorials/aspnet/running-demo.png -------------------------------------------------------------------------------- /assets/images/tutorials/aspnet/scripts-folder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ry/TypeScript-Handbook/3eda844624d4bfc0a9506f194a8b9d139dc002b3/assets/images/tutorials/aspnet/scripts-folder.png -------------------------------------------------------------------------------- /assets/images/tutorials/aspnet/src-folder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ry/TypeScript-Handbook/3eda844624d4bfc0a9506f194a8b9d139dc002b3/assets/images/tutorials/aspnet/src-folder.png -------------------------------------------------------------------------------- /assets/images/tutorials/aspnet/task-runner-explorer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ry/TypeScript-Handbook/3eda844624d4bfc0a9506f194a8b9d139dc002b3/assets/images/tutorials/aspnet/task-runner-explorer.png -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /pages/Basic Types.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | For programs to be useful, we need to be able to work with some of the simplest units of data: numbers, strings, structures, boolean values, and the like. 4 | In TypeScript, we support much the same types as you would expect in JavaScript, with a convenient enumeration type thrown in to help things along. 5 | 6 | # Boolean 7 | 8 | The most basic datatype is the simple true/false value, which JavaScript and TypeScript call a `boolean` value. 9 | 10 | ```ts 11 | let isDone: boolean = false; 12 | ``` 13 | 14 | # Number 15 | 16 | As in JavaScript, all numbers in TypeScript are floating point values. 17 | These floating point numbers get the type `number`. 18 | In addition to hexadecimal and decimal literals, TypeScript also supports binary and octal literals introduced in ECMAScript 2015. 19 | 20 | ```ts 21 | let decimal: number = 6; 22 | let hex: number = 0xf00d; 23 | let binary: number = 0b1010; 24 | let octal: number = 0o744; 25 | ``` 26 | 27 | # String 28 | 29 | Another fundamental part of creating programs in JavaScript for webpages and servers alike is working with textual data. 30 | As in other languages, we use the type `string` to refer to these textual datatypes. 31 | Just like JavaScript, TypeScript also uses double quotes (`"`) or single quotes (`'`) to surround string data. 32 | 33 | ```ts 34 | let color: string = "blue"; 35 | color = 'red'; 36 | ``` 37 | 38 | You can also use *template strings*, which can span multiple lines and have embedded expressions. 39 | These strings are surrounded by the backtick/backquote (`` ` ``) character, and embedded expressions are of the form `${ expr }`. 40 | 41 | ```ts 42 | let fullName: string = `Bob Bobbington`; 43 | let age: number = 37; 44 | let sentence: string = `Hello, my name is ${ fullName }. 45 | 46 | I'll be ${ age + 1 } years old next month.`; 47 | ``` 48 | 49 | This is equivalent to declaring `sentence` like so: 50 | 51 | ```ts 52 | let sentence: string = "Hello, my name is " + fullName + ".\n\n" + 53 | "I'll be " + (age + 1) + " years old next month."; 54 | ``` 55 | 56 | # Array 57 | 58 | TypeScript, like JavaScript, allows you to work with arrays of values. 59 | Array types can be written in one of two ways. 60 | In the first, you use the type of the elements followed by `[]` to denote an array of that element type: 61 | 62 | ```ts 63 | let list: number[] = [1, 2, 3]; 64 | ``` 65 | 66 | The second way uses a generic array type, `Array`: 67 | 68 | ```ts 69 | let list: Array = [1, 2, 3]; 70 | ``` 71 | 72 | # Tuple 73 | 74 | Tuple types allow you to express an array where the type of a fixed number of elements is known, but need not be the same. 75 | For example, you may want to represent a value as a pair of a `string` and a `number`: 76 | 77 | ```ts 78 | // Declare a tuple type 79 | let x: [string, number]; 80 | // Initialize it 81 | x = ["hello", 10]; // OK 82 | // Initialize it incorrectly 83 | x = [10, "hello"]; // Error 84 | ``` 85 | 86 | When accessing an element with a known index, the correct type is retrieved: 87 | 88 | ```ts 89 | console.log(x[0].substr(1)); // OK 90 | console.log(x[1].substr(1)); // Error, 'number' does not have 'substr' 91 | ``` 92 | 93 | When accessing an element outside the set of known indices, a union type is used instead: 94 | 95 | ```ts 96 | x[3] = "world"; // OK, 'string' can be assigned to 'string | number' 97 | 98 | console.log(x[5].toString()); // OK, 'string' and 'number' both have 'toString' 99 | 100 | x[6] = true; // Error, 'boolean' isn't 'string | number' 101 | ``` 102 | 103 | Union types are an advanced topic that we'll cover in a later chapter. 104 | 105 | # Enum 106 | 107 | A helpful addition to the standard set of datatypes from JavaScript is the `enum`. 108 | As in languages like C#, an enum is a way of giving more friendly names to sets of numeric values. 109 | 110 | ```ts 111 | enum Color {Red, Green, Blue} 112 | let c: Color = Color.Green; 113 | ``` 114 | 115 | By default, enums begin numbering their members starting at `0`. 116 | You can change this by manually setting the value of one of its members. 117 | For example, we can start the previous example at `1` instead of `0`: 118 | 119 | ```ts 120 | enum Color {Red = 1, Green, Blue} 121 | let c: Color = Color.Green; 122 | ``` 123 | 124 | Or, even manually set all the values in the enum: 125 | 126 | ```ts 127 | enum Color {Red = 1, Green = 2, Blue = 4} 128 | let c: Color = Color.Green; 129 | ``` 130 | 131 | A handy feature of enums is that you can also go from a numeric value to the name of that value in the enum. 132 | For example, if we had the value `2` but weren't sure what that mapped to in the `Color` enum above, we could look up the corresponding name: 133 | 134 | ```ts 135 | enum Color {Red = 1, Green, Blue} 136 | let colorName: string = Color[2]; 137 | 138 | alert(colorName); // Displays 'Green' as it's value is 2 above 139 | ``` 140 | 141 | # Any 142 | 143 | We may need to describe the type of variables that we do not know when we are writing an application. 144 | These values may come from dynamic content, e.g. from the user or a 3rd party library. 145 | In these cases, we want to opt-out of type-checking and let the values pass through compile-time checks. 146 | To do so, we label these with the `any` type: 147 | 148 | ```ts 149 | let notSure: any = 4; 150 | notSure = "maybe a string instead"; 151 | notSure = false; // okay, definitely a boolean 152 | ``` 153 | 154 | The `any` type is a powerful way to work with existing JavaScript, allowing you to gradually opt-in and opt-out of type-checking during compilation. 155 | You might expect `Object` to play a similar role, as it does in other languages. 156 | But variables of type `Object` only allow you to assign any value to them - you can't call arbitrary methods on them, even ones that actually exist: 157 | 158 | ```ts 159 | let notSure: any = 4; 160 | notSure.ifItExists(); // okay, ifItExists might exist at runtime 161 | notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check) 162 | 163 | let prettySure: Object = 4; 164 | prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'. 165 | ``` 166 | 167 | The `any` type is also handy if you know some part of the type, but perhaps not all of it. 168 | For example, you may have an array but the array has a mix of different types: 169 | 170 | ```ts 171 | let list: any[] = [1, true, "free"]; 172 | 173 | list[1] = 100; 174 | ``` 175 | 176 | # Void 177 | 178 | `void` is a little like the opposite of `any`: the absence of having any type at all. 179 | You may commonly see this as the return type of functions that do not return a value: 180 | 181 | ```ts 182 | function warnUser(): void { 183 | alert("This is my warning message"); 184 | } 185 | ``` 186 | 187 | Declaring variables of type `void` is not useful because you can only assign `undefined` or `null` to them: 188 | 189 | ```ts 190 | let unusable: void = undefined; 191 | ``` 192 | 193 | # Null and Undefined 194 | 195 | In TypeScript, both `undefined` and `null` actually have their own types named `undefined` and `null` respectively. 196 | Much like `void`, they're not extremely useful on their own: 197 | 198 | ```ts 199 | // Not much else we can assign to these variables! 200 | let u: undefined = undefined; 201 | let n: null = null; 202 | ``` 203 | 204 | By default `null` and `undefined` are subtypes of all other types. 205 | That means you can assign `null` and `undefined` to something like `number`. 206 | 207 | However, when using the `--strictNullChecks` flag, `null` and `undefined` are only assignable to `void` and their respective types. 208 | This helps avoid *many* common errors. 209 | In cases where you want to pass in either a `string` or `null` or `undefined`, you can use the union type `string | null | undefined`. 210 | Once again, more on union types later on. 211 | 212 | > As a note: we encourage the use of `--strictNullChecks` when possible, but for the purposes of this handbook, we will assume it is turned off. 213 | 214 | # Never 215 | 216 | The `never` type represents the type of values that never occur. 217 | For instance, `never` is the return type for a function expression or an arrow function expression that always throws an exception or one that never returns; 218 | Variables also acquire the type `never` when narrowed by any type guards that can never be true. 219 | 220 | The `never` type is a subtype of, and assignable to, every type; however, *no* type is a subtype of, or assignable to, `never` (except `never` itself). 221 | Even `any` isn't assignable to `never`. 222 | 223 | Some examples of functions returning `never`: 224 | 225 | ```ts 226 | // Function returning never must have unreachable end point 227 | function error(message: string): never { 228 | throw new Error(message); 229 | } 230 | 231 | // Inferred return type is never 232 | function fail() { 233 | return error("Something failed"); 234 | } 235 | 236 | // Function returning never must have unreachable end point 237 | function infiniteLoop(): never { 238 | while (true) { 239 | } 240 | } 241 | ``` 242 | 243 | # Type assertions 244 | 245 | Sometimes you'll end up in a situation where you'll know more about a value than TypeScript does. 246 | Usually this will happen when you know the type of some entity could be more specific than its current type. 247 | 248 | *Type assertions* are a way to tell the compiler "trust me, I know what I'm doing." 249 | A type assertion is like a type cast in other languages, but performs no special checking or restructuring of data. 250 | It has no runtime impact, and is used purely by the compiler. 251 | TypeScript assumes that you, the programmer, have performed any special checks that you need. 252 | 253 | Type assertions have two forms. 254 | One is the "angle-bracket" syntax: 255 | 256 | ```ts 257 | let someValue: any = "this is a string"; 258 | 259 | let strLength: number = (someValue).length; 260 | ``` 261 | 262 | And the other is the `as`-syntax: 263 | 264 | ```ts 265 | let someValue: any = "this is a string"; 266 | 267 | let strLength: number = (someValue as string).length; 268 | ``` 269 | 270 | The two samples are equivalent. 271 | Using one over the other is mostly a choice of preference; however, when using TypeScript with JSX, only `as`-style assertions are allowed. 272 | 273 | # A note about `let` 274 | 275 | You may've noticed that so far, we've been using the `let` keyword instead of JavaScript's `var` keyword which you might be more familiar with. 276 | The `let` keyword is actually a newer JavaScript construct that TypeScript makes available. 277 | We'll discuss the details later, but many common problems in JavaScript are alleviated by using `let`, so you should use it instead of `var` whenever possible. 278 | -------------------------------------------------------------------------------- /pages/Compiler Options in MSBuild.md: -------------------------------------------------------------------------------- 1 | ## Overview 2 | 3 | Compiler options can be specified using MSBuild properties within an MSBuild project. 4 | 5 | ## Example 6 | 7 | ```XML 8 | 9 | false 10 | true 11 | 12 | 13 | true 14 | false 15 | 16 | 19 | ``` 20 | 21 | ## Mappings 22 | 23 | Compiler Option | MSBuild Property Name | Allowed Values 24 | ---------------------------------------------|--------------------------------------------|----------------- 25 | `--allowJs` | *Not supported in MSBuild* | 26 | `--allowSyntheticDefaultImports` | TypeScriptAllowSyntheticDefaultImports | boolean 27 | `--allowUnreachableCode` | TypeScriptAllowUnreachableCode | boolean 28 | `--allowUnusedLabels` | TypeScriptAllowUnusedLabels | boolean 29 | `--alwaysStrict` | TypeScriptAlwaysStrict | boolean 30 | `--baseUrl` | TypeScriptBaseUrl | File path 31 | `--charset` | TypeScriptCharset | 32 | `--declaration` | TypeScriptGeneratesDeclarations | boolean 33 | `--declarationDir` | TypeScriptDeclarationDir | File path 34 | `--diagnostics` | *Not supported in MSBuild* | 35 | `--disableSizeLimit` | *Not supported in MSBuild* | 36 | `--emitBOM` | TypeScriptEmitBOM | boolean 37 | `--emitDecoratorMetadata` | TypeScriptEmitDecoratorMetadata | boolean 38 | `--experimentalAsyncFunctions` | TypeScriptExperimentalAsyncFunctions | boolean 39 | `--experimentalDecorators` | TypeScriptExperimentalDecorators | boolean 40 | `--forceConsistentCasingInFileNames` | TypeScriptForceConsistentCasingInFileNames | boolean 41 | `--help` | *Not supported in MSBuild* | 42 | `--importHelpers` | TypeScriptImportHelpers | boolean 43 | `--inlineSourceMap` | TypeScriptInlineSourceMap | boolean 44 | `--inlineSources` | TypeScriptInlineSources | boolean 45 | `--init` | *Not supported in MSBuild* | 46 | `--isolatedModules` | TypeScriptIsolatedModules | boolean 47 | `--jsx` | TypeScriptJSXEmit | `React` or `Preserve` 48 | `--jsxFactory` | TypeScriptJSXFactory | qualified name 49 | `--lib` | TypeScriptLib | Comma-separated list of strings 50 | `--listEmittedFiles` | *Not supported in MSBuild* | 51 | `--listFiles` | *Not supported in MSBuild* | 52 | `--locale` | *automatic* | Automatically set to PreferredUILang value 53 | `--mapRoot` | TypeScriptMapRoot | File path 54 | `--maxNodeModuleJsDepth` | *Not supported in MSBuild* | 55 | `--module` | TypeScriptModuleKind | `AMD`, `CommonJs`, `UMD`, `System` or `ES6` 56 | `--moduleResolution` | TypeScriptModuleResolution | `Classic` or `Node` 57 | `--newLine` | TypeScriptNewLine | `CRLF` or `LF` 58 | `--noEmit` | *Not supported in MSBuild* | 59 | `--noEmitHelpers` | TypeScriptNoEmitHelpers | boolean 60 | `--noEmitOnError` | TypeScriptNoEmitOnError | boolean 61 | `--noFallthroughCasesInSwitch` | TypeScriptNoFallthroughCasesInSwitch | boolean 62 | `--noImplicitAny` | TypeScriptNoImplicitAny | boolean 63 | `--noImplicitReturns` | TypeScriptNoImplicitReturns | boolean 64 | `--noImplicitThis` | TypeScriptNoImplicitThis | boolean 65 | `--noImplicitUseStrict` | TypeScriptNoImplicitUseStrict | boolean 66 | `--noStrictGenericChecks` | TypeScriptNoStrictGenericChecks | boolean 67 | `--noUnusedLocals` | TypeScriptNoUnusedLocals | boolean 68 | `--noUnusedParameters` | TypeScriptNoUnusedParameters | boolean 69 | `--noLib` | TypeScriptNoLib | boolean 70 | `--noResolve` | TypeScriptNoResolve | boolean 71 | `--out` | TypeScriptOutFile | File path 72 | `--outDir` | TypeScriptOutDir | File path 73 | `--outFile` | TypeScriptOutFile | File path 74 | `--paths` | *Not supported in MSBuild* | 75 | `--preserveConstEnums` | TypeScriptPreserveConstEnums | boolean 76 | `--preserveSymlinks` | TypeScriptPreserveSymlinks | boolean 77 | `--listEmittedFiles` | *Not supported in MSBuild* | 78 | `--pretty` | *Not supported in MSBuild* | 79 | `--reactNamespace` | TypeScriptReactNamespace | string 80 | `--removeComments` | TypeScriptRemoveComments | boolean 81 | `--rootDir` | TypeScriptRootDir | File path 82 | `--rootDirs` | *Not supported in MSBuild* | 83 | `--skipLibCheck` | TypeScriptSkipLibCheck | boolean 84 | `--skipDefaultLibCheck` | TypeScriptSkipDefaultLibCheck | boolean 85 | `--sourceMap` | TypeScriptSourceMap | File path 86 | `--sourceRoot` | TypeScriptSourceRoot | File path 87 | `--strict` | TypeScriptStrict | boolean 88 | `--strictFunctionTypes` | TypeScriptStrictFunctionTypes | boolean 89 | `--strictNullChecks` | TypeScriptStrictNullChecks | boolean 90 | `--stripInternal` | TypeScriptStripInternal | boolean 91 | `--suppressExcessPropertyErrors` | TypeScriptSuppressExcessPropertyErrors | boolean 92 | `--suppressImplicitAnyIndexErrors` | TypeScriptSuppressImplicitAnyIndexErrors | boolean 93 | `--target` | TypeScriptTarget | `ES3`, `ES5`, or `ES6` 94 | `--traceResolution` | *Not supported in MSBuild* | 95 | `--types` | *Not supported in MSBuild* | 96 | `--typeRoots` | *Not supported in MSBuild* | 97 | `--watch` | *Not supported in MSBuild* | 98 | *MSBuild only option* | TypeScriptAdditionalFlags | *Any compiler option* 99 | 100 | ## What is supported in my version of Visual Studio? 101 | 102 | Look in your `C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets` file. 103 | The authoritative mappings between MSBuild XML tags and `tsc` compiler options live in there. 104 | 105 | ## ToolsVersion 106 | 107 | The value of `1.7` property in the project file identifies the compiler version to use to build (1.7 in this example). 108 | This allows a project to build against the save versions of the compiler on different machines. 109 | 110 | If `TypeScriptToolsVersion` is not specified, the latest compiler version installed on the machine will be used to build. 111 | 112 | Users using newer versions of TS, will see a prompt to upgrade their project on first load. 113 | 114 | ## TypeScriptCompileBlocked 115 | 116 | If you are using a different build tool to build your project (e.g. gulp, grunt , etc.) and VS for the development and debugging experience, set `true` in your project. 117 | This should give you all the editing support, but not the build when you hit F5. 118 | -------------------------------------------------------------------------------- /pages/Enums.md: -------------------------------------------------------------------------------- 1 | # Enums 2 | 3 | Enums allow us to define a set of named constants. 4 | Using enums can make it easier to document intent, or create a set of distinct cases. 5 | TypeScript provides both numeric and string-based enums. 6 | 7 | ## Numeric enums 8 | 9 | We'll first start off with numeric enums, which are probably more familiar if you're coming from other languages. 10 | An enum can be defined using the `enum` keyword. 11 | 12 | ```ts 13 | enum Direction { 14 | Up = 1, 15 | Down, 16 | Left, 17 | Right, 18 | } 19 | ``` 20 | 21 | Above, we have a numeric enum where `Up` is initialized with `1`. 22 | All of the following members are auto-incremented from that point on. 23 | In other words, `Direction.Up` has the value `1`, `Down` has `2`, `Left` has `3`, and `Right` has `4`. 24 | 25 | If we wanted, we could leave off the initializers entirely: 26 | 27 | ```ts 28 | enum Direction { 29 | Up, 30 | Down, 31 | Left, 32 | Right, 33 | } 34 | ``` 35 | 36 | Here, `Up` would have the value `0`, `Down` would have `1`, etc. 37 | This auto-incrementing behavior is useful for cases where we might not care about the member values themselves, but do care that each value is distinct from other values in the same enum. 38 | 39 | Using an enum is simple: just access any member as a property off of the enum itself, and declare types using the name of the enum: 40 | 41 | ```ts 42 | enum Response { 43 | No = 0, 44 | Yes = 1, 45 | } 46 | 47 | function respond(recipient: string, message: Response): void { 48 | // ... 49 | } 50 | 51 | respond("Princess Caroline", Response.Yes) 52 | ``` 53 | 54 | Numeric enums can be mixed in [computed and constant members (see below)](#computed-and-constant-members). 55 | The short story is, enums without initializers either need to be first, or have to come after numeric enums initialized with numeric constants or other constant enum members. 56 | In other words, the following isn't allowed: 57 | 58 | ```ts 59 | enum E { 60 | A = getSomeValue(), 61 | B, // error! 'A' is not constant-initialized, so 'B' needs an initializer 62 | } 63 | ``` 64 | 65 | ## String enums 66 | 67 | String enums are a similar concept, but have some subtle [runtime differences](#enums-at-runtime) as documented below. 68 | In a string enum, each member has to be constant-initialized with a string literal, or with another string enum member. 69 | 70 | ```ts 71 | enum Direction { 72 | Up = "UP", 73 | Down = "DOWN", 74 | Left = "LEFT", 75 | Right = "RIGHT", 76 | } 77 | ``` 78 | 79 | While string enums don't have auto-incrementing behavior, string enums have the benefit that they "serialize" well. 80 | In other words, if you were debugging and had to read the runtime value of a numeric enum, the value is often opaque - it doesn't convey any useful meaning on its own (though [reverse mapping](#enums-at-runtime) can often help), string enums allow you to give a meaningful and readable value when your code runs, independent of the name of the enum member itself. 81 | 82 | ## Heterogeneous enums 83 | 84 | Technically enums can be mixed with string and numeric members, but it's not clear why you would ever want to do so: 85 | 86 | ```ts 87 | enum BooleanLikeHeterogeneousEnum { 88 | No = 0, 89 | Yes = "YES", 90 | } 91 | ``` 92 | 93 | Unless you're really trying to take advantage of JavaScript's runtime behavior in a clever way, it's advised that you don't do this. 94 | 95 | ## Computed and constant members 96 | 97 | Each enum member has a value associated with it which can be either *constant* or *computed*. 98 | An enum member is considered constant if: 99 | 100 | * It is the first member in the enum and it has no initializer, in which case it's assigned the value `0`: 101 | 102 | ```ts 103 | // E.X is constant: 104 | enum E { X } 105 | ``` 106 | 107 | * It does not have an initializer and the preceding enum member was a *numeric* constant. 108 | In this case the value of the current enum member will be the value of the preceding enum member plus one. 109 | 110 | ```ts 111 | // All enum members in 'E1' and 'E2' are constant. 112 | 113 | enum E1 { X, Y, Z } 114 | 115 | enum E2 { 116 | A = 1, B, C 117 | } 118 | ``` 119 | 120 | * The enum member is initialized with a constant enum expression. 121 | A constant enum expression is a subset of TypeScript expressions that can be fully evaluated at compile time. 122 | An expression is a constant enum expression if it is: 123 | 1. a literal enum expression (basically a string literal or a numeric literal) 124 | 2. a reference to previously defined constant enum member (which can originate from a different enum). 125 | 3. a parenthesized constant enum expression 126 | 4. one of the `+`, `-`, `~` unary operators applied to constant enum expression 127 | 5. `+`, `-`, `*`, `/`, `%`, `<<`, `>>`, `>>>`, `&`, `|`, `^` binary operators with constant enum expressions as operands 128 | It is a compile time error for constant enum expressions to be evaluated to `NaN` or `Infinity`. 129 | 130 | In all other cases enum member is considered computed. 131 | 132 | ```ts 133 | enum FileAccess { 134 | // constant members 135 | None, 136 | Read = 1 << 1, 137 | Write = 1 << 2, 138 | ReadWrite = Read | Write, 139 | // computed member 140 | G = "123".length 141 | } 142 | ``` 143 | 144 | ## Union enums and enum member types 145 | 146 | There is a special subset of constant enum members that aren't calculated: literal enum members. 147 | A literal enum member is a constant enum member with no initialized value, or with values that are initialized to 148 | 149 | * any string literal (e.g. `"foo"`, `"bar`, `"baz"`) 150 | * any numeric literal (e.g. `1`, `100`) 151 | * a unary minus applied to any numeric literal (e.g. `-1`, `-100`) 152 | 153 | When all members in an enum have literal enum values, some special semantics come to play. 154 | 155 | The first is that enum members also become types as well! 156 | For example, we can say that certain members can *only* have the value of an enum member: 157 | 158 | ```ts 159 | enum ShapeKind { 160 | Circle, 161 | Square, 162 | } 163 | 164 | interface Circle { 165 | kind: ShapeKind.Circle; 166 | radius: number; 167 | } 168 | 169 | interface Square { 170 | kind: ShapeKind.Square; 171 | sideLength: number; 172 | } 173 | 174 | let c: Circle = { 175 | kind: ShapeKind.Square, 176 | // ~~~~~~~~~~~~~~~~ Error! 177 | radius: 100, 178 | } 179 | ``` 180 | 181 | The other change is that enum types themselves effectively become a *union* of each enum member. 182 | While we haven't discussed [union types](./Advanced Types.md#union-types) yet, all that you need to know is that with union enums, the type system is able to leverage the fact that it knows the exact set of values that exist in the enum itself. 183 | Because of that, TypeScript can catch silly bugs where we might be comparing values incorrectly. 184 | For example: 185 | 186 | ```ts 187 | enum E { 188 | Foo, 189 | Bar, 190 | } 191 | 192 | function f(x: E) { 193 | if (x !== E.Foo || x !== E.Bar) { 194 | // ~~~~~~~~~~~ 195 | // Error! Operator '!==' cannot be applied to types 'E.Foo' and 'E.Bar'. 196 | } 197 | } 198 | ``` 199 | 200 | In that example, we first checked whether `x` was *not* `E.Foo`. 201 | If that check succeeds, then our `||` will short-circuit, and the body of the 'if' will get run. 202 | However, if the check didn't succeed, then `x` can *only* be `E.Foo`, so it doesn't make sense to see whether it's equal to `E.Bar`. 203 | 204 | ## Enums at runtime 205 | 206 | Enums are real objects that exist at runtime. 207 | For example, the following enum 208 | 209 | ```ts 210 | enum E { 211 | X, Y, Z 212 | } 213 | ``` 214 | 215 | can actually be passed around to functions 216 | 217 | ```ts 218 | function f(obj: { X: number }) { 219 | return obj.X; 220 | } 221 | 222 | // Works, since 'E' has a property named 'X' which is a number. 223 | f(E); 224 | ``` 225 | 226 | ### Reverse mappings 227 | 228 | In addition to creating an object with property names for members, numeric enums members also get a *reverse mapping* from enum values to enum names. 229 | For example, in this example: 230 | 231 | ```ts 232 | enum Enum { 233 | A 234 | } 235 | let a = Enum.A; 236 | let nameOfA = Enum[a]; // "A" 237 | ``` 238 | 239 | TypeScript might compile this down to something like the the following JavaScript: 240 | 241 | ```js 242 | var Enum; 243 | (function (Enum) { 244 | Enum[Enum["A"] = 0] = "A"; 245 | })(Enum || (Enum = {})); 246 | var a = Enum.A; 247 | var nameOfA = Enum[a]; // "A" 248 | ``` 249 | 250 | In this generated code, an enum is compiled into an object that stores both forward (`name` -> `value`) and reverse (`value` -> `name`) mappings. 251 | References to other enum members are always emitted as property accesses and never inlined. 252 | 253 | Keep in mind that string enum members *do not* get a reverse mapping generated at all. 254 | 255 | ### `const` enums 256 | 257 | In most cases, enums are a perfectly valid solution. 258 | However sometimes requirements are tighter. 259 | To avoid paying the cost of extra generated code and additional indirection when accessing enum values, it's possible to use `const` enums. 260 | Const enums are defined using the `const` modifier on our enums: 261 | 262 | ```ts 263 | const enum Enum { 264 | A = 1, 265 | B = A * 2 266 | } 267 | ``` 268 | 269 | Const enums can only use constant enum expressions and unlike regular enums they are completely removed during compilation. 270 | Const enum members are inlined at use sites. 271 | This is possible since const enums cannot have computed members. 272 | 273 | ```ts 274 | const enum Directions { 275 | Up, 276 | Down, 277 | Left, 278 | Right 279 | } 280 | 281 | let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right] 282 | ``` 283 | 284 | in generated code will become 285 | 286 | ```js 287 | var directions = [0 /* Up */, 1 /* Down */, 2 /* Left */, 3 /* Right */]; 288 | ``` 289 | 290 | ## Ambient enums 291 | 292 | Ambient enums are used to describe the shape of already existing enum types. 293 | 294 | ```ts 295 | declare enum Enum { 296 | A = 1, 297 | B, 298 | C = 2 299 | } 300 | ``` 301 | 302 | One important difference between ambient and non-ambient enums is that, in regular enums, members that don't have an initializer will be considered constant if its preceding enum member is considered constant. 303 | In contrast, an ambient (and non-const) enum member that does not have initializer is *always* considered computed. 304 | -------------------------------------------------------------------------------- /pages/Integrating with Build Tools.md: -------------------------------------------------------------------------------- 1 | Build tools 2 | 3 | * [Browserify](#browserify) 4 | * [Duo](#duo) 5 | * [Grunt](#grunt) 6 | * [Gulp](#gulp) 7 | * [Jspm](#jspm) 8 | * [Webpack](#webpack) 9 | * [MSBuild](#msbuild) 10 | * [NuGet](#nuget) 11 | 12 | # Browserify 13 | 14 | ### Install 15 | 16 | ```sh 17 | npm install tsify 18 | ``` 19 | 20 | ### Using Command Line Interface 21 | 22 | ```sh 23 | browserify main.ts -p [ tsify --noImplicitAny ] > bundle.js 24 | ``` 25 | 26 | ### Using API 27 | 28 | ```js 29 | var browserify = require("browserify"); 30 | var tsify = require("tsify"); 31 | 32 | browserify() 33 | .add("main.ts") 34 | .plugin("tsify", { noImplicitAny: true }) 35 | .bundle() 36 | .pipe(process.stdout); 37 | ``` 38 | 39 | More details: [smrq/tsify](https://github.com/smrq/tsify) 40 | 41 | # Duo 42 | 43 | ### Install 44 | 45 | ```sh 46 | npm install duo-typescript 47 | ``` 48 | 49 | ### Using Command Line Interface 50 | 51 | ```sh 52 | duo --use duo-typescript entry.ts 53 | ``` 54 | 55 | ### Using API 56 | 57 | ```js 58 | var Duo = require("duo"); 59 | var fs = require("fs") 60 | var path = require("path") 61 | var typescript = require("duo-typescript"); 62 | 63 | var out = path.join(__dirname, "output.js") 64 | 65 | Duo(__dirname) 66 | .entry("entry.ts") 67 | .use(typescript()) 68 | .run(function (err, results) { 69 | if (err) throw err; 70 | // Write compiled result to output file 71 | fs.writeFileSync(out, results.code); 72 | }); 73 | ``` 74 | 75 | More details: [frankwallis/duo-typescript](https://github.com/frankwallis/duo-typescript) 76 | 77 | # Grunt 78 | 79 | ### Install 80 | 81 | ```sh 82 | npm install grunt-ts 83 | ``` 84 | 85 | ### Basic Gruntfile.js 86 | 87 | ````js 88 | module.exports = function(grunt) { 89 | grunt.initConfig({ 90 | ts: { 91 | default : { 92 | src: ["**/*.ts", "!node_modules/**/*.ts"] 93 | } 94 | } 95 | }); 96 | grunt.loadNpmTasks("grunt-ts"); 97 | grunt.registerTask("default", ["ts"]); 98 | }; 99 | ```` 100 | 101 | More details: [TypeStrong/grunt-ts](https://github.com/TypeStrong/grunt-ts) 102 | 103 | # Gulp 104 | 105 | ### Install 106 | 107 | ```sh 108 | npm install gulp-typescript 109 | ``` 110 | 111 | ### Basic gulpfile.js 112 | 113 | ```js 114 | var gulp = require("gulp"); 115 | var ts = require("gulp-typescript"); 116 | 117 | gulp.task("default", function () { 118 | var tsResult = gulp.src("src/*.ts") 119 | .pipe(ts({ 120 | noImplicitAny: true, 121 | out: "output.js" 122 | })); 123 | return tsResult.js.pipe(gulp.dest("built/local")); 124 | }); 125 | ``` 126 | 127 | More details: [ivogabe/gulp-typescript](https://github.com/ivogabe/gulp-typescript) 128 | 129 | # Jspm 130 | 131 | ### Install 132 | 133 | ```sh 134 | npm install -g jspm@beta 135 | ``` 136 | 137 | _Note: Currently TypeScript support in jspm is in 0.16beta_ 138 | 139 | More details: [TypeScriptSamples/jspm](https://github.com/Microsoft/TypeScriptSamples/tree/master/jspm) 140 | 141 | # Webpack 142 | 143 | ### Install 144 | 145 | ```sh 146 | npm install ts-loader --save-dev 147 | ``` 148 | 149 | ### Basic webpack.config.js 150 | 151 | ```js 152 | module.exports = { 153 | entry: "./src/index.tsx", 154 | output: { 155 | filename: "bundle.js" 156 | }, 157 | resolve: { 158 | // Add '.ts' and '.tsx' as a resolvable extension. 159 | extensions: ["", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"] 160 | }, 161 | module: { 162 | loaders: [ 163 | // all files with a '.ts' or '.tsx' extension will be handled by 'ts-loader' 164 | { test: /\.tsx?$/, loader: "ts-loader" } 165 | ] 166 | } 167 | } 168 | ``` 169 | 170 | See [more details on ts-loader here](https://www.npmjs.com/package/ts-loader). 171 | 172 | Alternatives: 173 | 174 | * [awesome-typescript-loader](https://www.npmjs.com/package/awesome-typescript-loader) 175 | 176 | # MSBuild 177 | 178 | Update project file to include locally installed `Microsoft.TypeScript.Default.props` (at the top) and `Microsoft.TypeScript.targets` (at the bottom) files: 179 | 180 | ```xml 181 | 182 | 183 | 184 | 187 | 188 | 189 | 190 | false 191 | true 192 | 193 | 194 | true 195 | false 196 | 197 | 198 | 199 | 202 | 203 | ``` 204 | 205 | More details about defining MSBuild compiler options: [Setting Compiler Options in MSBuild projects](./Compiler Options in MSBuild.md) 206 | 207 | # NuGet 208 | 209 | * Right-Click -> Manage NuGet Packages 210 | * Search for `Microsoft.TypeScript.MSBuild` 211 | * Hit `Install` 212 | * When install is complete, rebuild! 213 | 214 | More details can be found at [Package Manager Dialog](http://docs.nuget.org/Consume/Package-Manager-Dialog) and [using nightly builds with NuGet](https://github.com/Microsoft/TypeScript/wiki/Nightly-drops#using-nuget-with-msbuild) 215 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 ` 177 | 178 | 179 | 180 | 181 | 182 | 183 | ``` 184 | 185 | Notice that we're including files from within `node_modules`. 186 | React and React-DOM's npm packages include standalone `.js` files that you can include in a web page, and we're referencing them directly to get things moving faster. 187 | Feel free to copy these files to another directory, or alternatively, host them on a content delivery network (CDN). 188 | Facebook makes CDN-hosted versions of React available, and you can [read more about that here](http://facebook.github.io/react/downloads.html#development-vs.-production-builds). 189 | 190 | # Create a webpack configuration file 191 | 192 | Create a `webpack.config.js` file at the root of the project directory. 193 | 194 | ```js 195 | module.exports = { 196 | entry: "./src/index.tsx", 197 | output: { 198 | filename: "bundle.js", 199 | path: __dirname + "/dist" 200 | }, 201 | 202 | // Enable sourcemaps for debugging webpack's output. 203 | devtool: "source-map", 204 | 205 | resolve: { 206 | // Add '.ts' and '.tsx' as resolvable extensions. 207 | extensions: [".ts", ".tsx", ".js", ".json"] 208 | }, 209 | 210 | module: { 211 | rules: [ 212 | // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'. 213 | { test: /\.tsx?$/, loader: "awesome-typescript-loader" }, 214 | 215 | // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. 216 | { enforce: "pre", test: /\.js$/, loader: "source-map-loader" } 217 | ] 218 | }, 219 | 220 | // When importing a module whose path matches one of the following, just 221 | // assume a corresponding global variable exists and use that instead. 222 | // This is important because it allows us to avoid bundling all of our 223 | // dependencies, which allows browsers to cache those libraries between builds. 224 | externals: { 225 | "react": "React", 226 | "react-dom": "ReactDOM" 227 | }, 228 | }; 229 | ``` 230 | 231 | You might be wondering about that `externals` field. 232 | We want to avoid bundling all of React into the same file, since this increases compilation time and browsers will typically be able to cache a library if it doesn't change. 233 | 234 | Ideally, we'd just import the React module from within the browser, but most browsers still don't quite support modules yet. 235 | Instead libraries have traditionally made themselves available using a single global variable like `jQuery` or `_`. 236 | This is called the "namespace pattern", and webpack allows us to continue leveraging libraries written that way. 237 | With our entry for `"react": "React"`, webpack will work its magic to make any import of `"react"` load from the `React` variable. 238 | 239 | You can learn more about configuring webpack [here](https://webpack.js.org/concepts). 240 | 241 | # Putting it all together 242 | 243 | Just run: 244 | 245 | ```shell 246 | webpack 247 | ``` 248 | 249 | Now open up `index.html` in your favorite browser and everything should be ready to use! 250 | You should see a page that says "Hello from TypeScript and React!" 251 | -------------------------------------------------------------------------------- /pages/tutorials/TypeScript in 5 minutes.md: -------------------------------------------------------------------------------- 1 | Let's get started by building a simple web application with TypeScript. 2 | 3 | ## Installing TypeScript 4 | 5 | There are two main ways to get the TypeScript tools: 6 | 7 | * Via npm (the Node.js package manager) 8 | * By installing TypeScript's Visual Studio plugins 9 | 10 | Visual Studio 2017 and Visual Studio 2015 Update 3 include TypeScript by default. 11 | If you didn't install TypeScript with Visual Studio, you can still [download it](/#download-links). 12 | 13 | For NPM users: 14 | 15 | ```shell 16 | > npm install -g typescript 17 | ``` 18 | 19 | ## Building your first TypeScript file 20 | 21 | In your editor, type the following JavaScript code in `greeter.ts`: 22 | 23 | ```ts 24 | function greeter(person) { 25 | return "Hello, " + person; 26 | } 27 | 28 | let user = "Jane User"; 29 | 30 | document.body.innerHTML = greeter(user); 31 | ``` 32 | 33 | ## Compiling your code 34 | 35 | We used a `.ts` extension, but this code is just JavaScript. 36 | You could have copy/pasted this straight out of an existing JavaScript app. 37 | 38 | At the command line, run the TypeScript compiler: 39 | 40 | ```shell 41 | tsc greeter.ts 42 | ``` 43 | 44 | The result will be a file `greeter.js` which contains the same JavaScript that you fed in. 45 | We're up and running using TypeScript in our JavaScript app! 46 | 47 | Now we can start taking advantage of some of the new tools TypeScript offers. 48 | Add a `: string` type annotation to the 'person' function argument as shown here: 49 | 50 | ```ts 51 | function greeter(person: string) { 52 | return "Hello, " + person; 53 | } 54 | 55 | let user = "Jane User"; 56 | 57 | document.body.innerHTML = greeter(user); 58 | ``` 59 | 60 | ## Type annotations 61 | 62 | Type annotations in TypeScript are lightweight ways to record the intended contract of the function or variable. 63 | In this case, we intend the greeter function to be called with a single string parameter. 64 | We can try changing the call greeter to pass an array instead: 65 | 66 | ```ts 67 | function greeter(person: string) { 68 | return "Hello, " + person; 69 | } 70 | 71 | let user = [0, 1, 2]; 72 | 73 | document.body.innerHTML = greeter(user); 74 | ``` 75 | 76 | Re-compiling, you'll now see an error: 77 | 78 | ```shell 79 | error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'string'. 80 | ``` 81 | 82 | Similarly, try removing all the arguments to the greeter call. 83 | TypeScript will let you know that you have called this function with an unexpected number of parameters. 84 | In both cases, TypeScript can offer static analysis based on both the structure of your code, and the type annotations you provide. 85 | 86 | Notice that although there were errors, the `greeter.js` file is still created. 87 | You can use TypeScript even if there are errors in your code. But in this case, TypeScript is warning that your code will likely not run as expected. 88 | 89 | ## Interfaces 90 | 91 | Let's develop our sample further. Here we use an interface that describes objects that have a firstName and lastName field. 92 | In TypeScript, two types are compatible if their internal structure is compatible. 93 | This allows us to implement an interface just by having the shape the interface requires, without an explicit `implements` clause. 94 | 95 | ```ts 96 | interface Person { 97 | firstName: string; 98 | lastName: string; 99 | } 100 | 101 | function greeter(person: Person) { 102 | return "Hello, " + person.firstName + " " + person.lastName; 103 | } 104 | 105 | let user = { firstName: "Jane", lastName: "User" }; 106 | 107 | document.body.innerHTML = greeter(user); 108 | ``` 109 | 110 | ## Classes 111 | 112 | Finally, let's extend the example one last time with classes. 113 | TypeScript supports new features in JavaScript, like support for class-based object-oriented programming. 114 | 115 | Here we're going to create a `Student` class with a constructor and a few public fields. 116 | Notice that classes and interfaces play well together, letting the programmer decide on the right level of abstraction. 117 | 118 | Also of note, the use of `public` on arguments to the constructor is a shorthand that allows us to automatically create properties with that name. 119 | 120 | ```ts 121 | class Student { 122 | fullName: string; 123 | constructor(public firstName: string, public middleInitial: string, public lastName: string) { 124 | this.fullName = firstName + " " + middleInitial + " " + lastName; 125 | } 126 | } 127 | 128 | interface Person { 129 | firstName: string; 130 | lastName: string; 131 | } 132 | 133 | function greeter(person : Person) { 134 | return "Hello, " + person.firstName + " " + person.lastName; 135 | } 136 | 137 | let user = new Student("Jane", "M.", "User"); 138 | 139 | document.body.innerHTML = greeter(user); 140 | ``` 141 | 142 | Re-run `tsc greeter.ts` and you'll see the generated JavaScript is the same as the earlier code. 143 | Classes in TypeScript are just a shorthand for the same prototype-based OO that is frequently used in JavaScript. 144 | 145 | ## Running your TypeScript web app 146 | 147 | Now type the following in `greeter.html`: 148 | 149 | ```html 150 | 151 | 152 | TypeScript Greeter 153 | 154 | 155 | 156 | 157 | ``` 158 | 159 | Open `greeter.html` in the browser to run your first simple TypeScript web application! 160 | 161 | Optional: Open `greeter.ts` in Visual Studio, or copy the code into the TypeScript playground. 162 | You can hover over identifiers to see their types. 163 | Notice that in some cases these types are inferred automatically for you. 164 | Re-type the last line, and see completion lists and parameter help based on the types of the DOM elements. 165 | Put your cursor on the reference to the greeter function, and hit F12 to go to its definition. 166 | Notice, too, that you can right-click on a symbol and use refactoring to rename it. 167 | 168 | The type information provided works together with the tools to work with JavaScript at application scale. 169 | For more examples of what's possible in TypeScript, see the Samples section of the website. 170 | 171 | ![Visual Studio picture](/assets/images/docs/greet_person.png) 172 | -------------------------------------------------------------------------------- /pull_request_template.md: -------------------------------------------------------------------------------- 1 | 16 | 17 | Fixes # 18 | --------------------------------------------------------------------------------