├── 'this'-in-TypeScript.md
├── .github
└── workflows
│ ├── sync
│ └── sync.yml
├── .gitignore
├── .vscode
└── settings.json
├── API-Breaking-Changes.md
├── All-The-Bots.md
├── Architectural-Overview.md
├── Blog-Post-Ideas.md
├── Breaking-Changes.md
├── Cancellation-Support-in-tsserver.md
├── Coding-guidelines.md
├── Common-Errors.md
├── Compiler-Internals.md
├── Compiler-Options.md
├── Configuring-MSBuild-projects-to-use-NuGet.md
├── Contributing-to-TypeScript.md
├── Debugging-Language-Service-in-VS-Code.md
├── Docker-Quickstart.md
├── FAQ.md
├── FAQs-for-API-Consumers.md
├── Getting-logs-from-TS-Server-in-VS-Code.md
├── Home.md
├── How-the-User-Tests-Work.md
├── How-to-maintain-Definitely-Typed-tests.md
├── Integrating-with-Build-Tools.md
├── JSDoc-support-in-JavaScript.md
├── JSX.md
├── JavaScript-Language-Service-in-Visual-Studio.md
├── LICENSE
├── Nightly-drops.md
├── No-New-Utility-Types.md
├── Node-Target-Mapping.md
├── Performance-Tracing.md
├── Performance.md
├── Preferred-Issue-Titles.md
├── Providing-Visual-Studio-Repro-Steps.md
├── README.md
├── Release-Activities.md
├── Resources.md
├── Roadmap.md
├── SECURITY.md
├── Setting-Compiler-Options-in-MSBuild-projects.md
├── Spec conformance testing.md
├── Standalone-Server-(tsserver).md
├── Tooling-On-The-Compiler-Repo.md
├── Triage-Instructions.md
├── Triggering-TypeScript-Bot.md
├── Type-Checking-JavaScript-Files.md
├── TypeScript's-Release-Process.md
├── TypeScript-Deployment.md
├── TypeScript-Design-Goals.md
├── TypeScript-Editor-Support.md
├── TypeScript-MSBuild-In-Depth.md
├── Typings-for-npm-packages.md
├── Updating-TypeScript-in-Visual-Studio-2017.md
├── Useful-Links-for-TypeScript-Issue-Management.md
├── Using-TypeScript-With-ASP.NET-5.md
├── Using-the-Compiler-API-(TypeScript-1.4).md
├── Using-the-Compiler-API.md
├── Using-the-Language-Service-API.md
├── Using-the-New-Language-Service-in-Visual-Studio-15-Preview.md
├── What's-new-in-TypeScript.md
├── Writing-Good-Design-Proposals.md
├── Writing-a-Language-Service-Plugin.md
├── _Footer.md
├── _Sidebar.md
├── aspnet-screenshots
├── add-tsconfig.png
├── compile-on-save.png
├── new-project.png
├── postbuild.png
├── project.png
└── virtual-project.png
├── codebase
├── compiler
│ ├── Codebase-Compiler-Binder.md
│ ├── Codebase-Compiler-Checker.md
│ ├── Codebase-Compiler-Emitter.md
│ ├── Codebase-Compiler-FAQ.md
│ ├── Codebase-Compiler-Parser.md
│ ├── Codebase-Compiler-Scanner.md
│ ├── Codebase-Compiler-Services.md
│ ├── Codebase-Compiler-Types.md
│ └── Codebase-Compiler-Utils.md
└── services
│ ├── Codebase-Services-Completions.md
│ └── Codebase-Services-TextChanges.md
├── debugging
└── README.md
├── dev-mode-screenshots
├── 001.png
├── 002.png
├── 003.png
├── 004.png
├── 005.png
└── 006.png
├── images
├── addNewPackageSource.PNG
├── architecture.png
├── array.map.png
├── decl1.png
├── destructuring.png
├── enable-salsa-dev15.png
├── new-in-typescript
│ ├── pretty01.png
│ └── tsconfig-in-vs.png
├── react.png
├── searchForMyGetPackage.PNG
├── searchForNuGetPackage.png
├── tracingCheckVariableDeclaration.png
├── tracingExpanded.png
├── tracingJustOpened.png
└── tracingTypes.png
├── package.json
├── reference
├── Reference-Checker-Inference.md
├── Reference-Checker-Widening-Narrowing.md
└── test.md
├── scripts
├── convertRelativeLinksToHardcoded.js
└── fixtures
│ └── input.md
└── tsconfig.json.md
/'this'-in-TypeScript.md:
--------------------------------------------------------------------------------
1 | ## Introduction
2 | The `this` keyword in JavaScript (and thus TypeScript) behaves differently than it does in many other languages. This can be very surprising, especially for users of other languages that have certain intuitions about how `this` should work.
3 |
4 | This page will teach you how to recognize and diagnose problems with `this` in TypeScript, and describes several solutions and their respective trade-offs.
5 |
6 | ## Typical Symptoms and Risk Factors
7 | Typical symptoms of a lost `this` context include:
8 | * A class field (`this.foo`) is `undefined` when some other value was expected
9 | * The value `this` points to the global `window` object instead of the class instance (non-strict mode)
10 | * The value `this` points `undefined` instead of the class instance (strict mode)
11 | * Invoking a class method (`this.doBar()`) fails with the error "TypeError: undefined is not a function", "Object doesn't support property or method 'doBar'", or "this.doBar is not a function"
12 |
13 | These things often happen in certain coding patterns:
14 | * Event listeners, e.g. `window.addEventListener('click', myClass.doThing);`
15 | * Promise resolution, e.g. `myPromise.then(myClass.theNextThing);`
16 | * Library event callbacks, e.g. `$(document).ready(myClass.start);`
17 | * Functional callbacks, e.g. `someArray.map(myClass.convert)`
18 | * Classes in ViewModel-type libraries, e.g. `
`
19 | * Functions in options bags, e.g. `$.ajax(url, { success: myClass.handleData })`
20 |
21 | ## What is `this` in JavaScript?
22 | Much has been written about the hazards of `this` in JavaScript. See [this page](http://www.quirksmode.org/js/this.html), [this one](http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/), or [this other one](http://bjorn.tipling.com/all-this).
23 |
24 | When a function is invoked in JavaScript, you can follow these steps to determine what `this` will be (these rules are in priority order):
25 | * If the function was the result of a call to `function#bind`, `this` will be the argument given to `bind`
26 | * If the function was invoked in the form `foo.func()`, `this` will be `foo`
27 | * If in strict mode, `this` will be `undefined`
28 | * Otherwise, `this` will be the global object (`window` in a browser)
29 |
30 | These rules can result in some counter-intuitive behavior. For example:
31 | ```ts
32 | class Foo {
33 | x = 3;
34 | print() {
35 | console.log('x is ' + this.x);
36 | }
37 | }
38 |
39 | var f = new Foo();
40 | f.print(); // Prints 'x is 3' as expected
41 |
42 | // Use the class method in an object literal
43 | var z = { x: 10, p: f.print };
44 | z.p(); // Prints 'x is 10'
45 |
46 | var p = z.p;
47 | p(); // Prints 'x is undefined'
48 | ```
49 |
50 | ## Red Flags for `this`
51 | The biggest red flag you can keep in mind is *the use of a class method without immediately invoking it*. Any time you see a class method being *referenced* without being *invoked* as part of that same expression, `this` might be incorrect.
52 |
53 | Examples:
54 | ```ts
55 | var x = new MyObject();
56 | x.printThing(); // SAFE, method is invoked where it is referenced
57 |
58 | var y = x.printThing; // DANGER, invoking 'y()' may not have correct 'this'
59 |
60 | window.addEventListener('click', x.printThing, 10); // DANGER, method is not invoked where it is referenced
61 |
62 | window.addEventListener('click', () => x.printThing(), 10); // SAFE, method is invoked in the same expression
63 | ```
64 |
65 | ## Fixes
66 | There are several ways to correctly keep your `this` context.
67 |
68 | ### Use Instance Functions
69 | Instead of using a *prototype* method, the default for methods in TypeScript, you can use an *instance arrow function* to define a class member:
70 | ```ts
71 | class MyClass {
72 | private status = "blah";
73 |
74 | public run = () => { // <-- note syntax here
75 | alert(this.status);
76 | }
77 | }
78 | var x = new MyClass();
79 | $(document).ready(x.run); // SAFE, 'run' will always have correct 'this'
80 | ```
81 |
82 | * Good/bad: This creates an additional closure per method per instance of the class. If this method is usually only used in regular method calls, this is overkill. However, if it's used a lot in callback positions, it's more efficient for the class instance to capture the `this` context instead of each call site creating a new closure upon invoke.
83 | * Good: Impossible for external callers to forget to handle `this` context
84 | * Good: Typesafe in TypeScript
85 | * Good: No extra work if the function has parameters
86 | * Bad: Derived classes can't call base class methods written this way using `super`
87 | * Bad: The exact semantics of which methods are "pre-bound" and which aren't create an additional non-typesafe contract between the class and its consumers
88 |
89 | ### Local Fat Arrow
90 | In TypeScript (shown here with some dummy parameters for explanatory reasons):
91 |
92 | ```ts
93 | var x = new SomeClass();
94 | someCallback((n, m) => x.doSomething(n, m));
95 | ```
96 |
97 | * Good/bad: Opposite memory/performance trade-off compared to instance functions
98 | * Good: In TypeScript, this has 100% type safety
99 | * Good: Works in ECMAScript 3
100 | * Good: You only have to type the instance name once
101 | * Bad: You'll have to type the parameters twice
102 | * Bad: Doesn't work with variadic ('rest') parameters
103 |
104 | ### Function.bind
105 | ```ts
106 | var x = new SomeClass();
107 | // SAFE: Functions created from function.bind always preserve 'this'
108 | window.setTimeout(x.someMethod.bind(x), 100);
109 | ```
110 |
111 | * Good/bad: Opposite memory/performance trade-off compared to using instance functions
112 | * Good: No extra work if the function has parameters
113 | * Bad: In TypeScript, this currently has no type safety
114 | * Bad: Only available in [ECMAScript 5](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) or newer
115 | * Bad: You have to type the instance name twice
116 |
117 | ### Specify type of `this` in function signature
118 | See details [here](https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters).
119 |
120 | ```ts
121 | interface SomeEvent {
122 | cancelable: boolean;
123 | preventDefault(): void;
124 | }
125 |
126 | function eventHandler(this: SomeEvent) {
127 | if (this.cancelable) {
128 | this.preventDefault();
129 | }
130 | // ...
131 | }
132 | ```
133 |
134 | * Good: The function has type information of the context it is supposed to run in, which is helpful in type checking and IDE completion
135 | * Bad: The syntax of having `this` type declaration among function arguments might be confusing for developers at reading-time
136 |
--------------------------------------------------------------------------------
/.github/workflows/sync:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # This script implements a two-way mirroring bewteen a GH wiki for a repo `R`
4 | # (called `DOTREMOTE` below) with a public repo `R-wiki` (intended for external
5 | # contributions, called `DASHREMOTE` below). See `sync.yml` for how it is
6 | # triggered: it is a minimal-ish yaml file that should be added to both sides
7 | # (`R` and `R-wiki`), with a `push` trigger on `R-wiki` (and optionally a
8 | # schedule) and a `gollum` trigger on `R`. The action spec is careful to
9 | # always checkout `R-wiki` (`DASHREMOTE`) since checking out `R` would be
10 | # useless. It then merges in changes in `DOTREMOTE` and pushes the results to
11 | # both. Pushing the merged version will trigger an action on the other side,
12 | # but that would be very quick (both the `merge` and pushing it will be
13 | # no-ops.)
14 |
15 | set -ue
16 | shopt -s extglob
17 |
18 | PUSHER="${PUSHER// +( )/ }"; PUSHER="${PUSHER# }"; PUSHER="${PUSHER% }"
19 | NAME="${PUSHER% <*}"
20 | EMAIL="${PUSHER##* <}"; EMAIL="${EMAIL%>}"
21 | echo "Setting git username to \"$NAME\" and email to \"$EMAIL\""
22 | export GIT_AUTHOR_NAME="$NAME"
23 | export GIT_AUTHOR_EMAIL="$EMAIL"
24 | export GIT_COMMITTER_NAME="$NAME"
25 | export GIT_COMMITTER_EMAIL="$EMAIL"
26 |
27 | DASHREMOTE="$(git remote get-url origin)"
28 | DOTREMOTE="${DASHREMOTE//-wiki/.wiki}"
29 | echo "DASHREMOTE = $DASHREMOTE, DOTREMOTE = $DOTREMOTE"
30 |
31 | for r in "$DASHREMOTE" "$DOTREMOTE"; do
32 | if [[ "$(git ls-remote --symref "$r" HEAD | grep "^ref:")" \
33 | != $'ref: refs/heads/master\tHEAD' ]]; then
34 | echo "Unexpected branch name at $r: expected to see \"master\""
35 | fi
36 | done
37 |
38 | echo ">>> Adding and fetching DOTREMOTE"
39 | git remote add dot "$DOTREMOTE"
40 | git fetch dot
41 |
42 | echo ">>> Merging changes"
43 | git pull --no-edit --no-rebase dot "master"
44 |
45 | echo ">>> Pushing merges to DASHREMOTE"
46 | git push origin
47 |
48 | echo ">>> Pushing merges to DOTREMOTE"
49 | git push dot main:master
50 |
--------------------------------------------------------------------------------
/.github/workflows/sync.yml:
--------------------------------------------------------------------------------
1 | # Roughly based on
2 | # https://www.growingwiththeweb.com/2016/07/enabling-pull-requests-on-github-wikis.html
3 |
4 | name: Sync Two Wiki Repos
5 |
6 | on:
7 | push: {branches: [main]}
8 | schedule: [{cron: "7 0 * * 1,3"}] # https://crontab.guru/#7_0_*_*_1,3
9 | workflow_dispatch: # on request
10 |
11 | jobs:
12 | sync:
13 | runs-on: ubuntu-latest
14 | steps:
15 | - name: Get repo name
16 | run: R=${GITHUB_REPOSITORY%?wiki}; echo "BASENAME=${R##*/}" >> $GITHUB_ENV
17 | - name: Checkout ${{ env.BASENAME }}-wiki
18 | uses: actions/checkout@v4
19 | with:
20 | repository: "${{ GITHUB.repository_owner }}/${{ env.BASENAME }}-wiki"
21 | token: ${{ secrets.TS_BOT_TOKEN }}
22 | fetch-depth: 0
23 | - name: Run sync
24 | run: ./.github/workflows/sync
25 | env:
26 | PUSHER: typescript-bot
27 | AUTH: ${{ secrets.TS_BOT_TOKEN }}
28 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | yarn.lock
2 | node_modules/
3 | package-lock.json
4 | TypeScript
5 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "[markdown]": {
3 | "editor.rulers": [
4 | 80
5 | ],
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/All-The-Bots.md:
--------------------------------------------------------------------------------
1 | This is a list of the services that post as typescript-bot.
2 |
3 | ## TypeScript repo
4 |
5 | - [GitHub Actions - close issues](https://github.com/microsoft/TypeScript/blob/main/.github/workflows/close-issues.yml)
6 | - [GitHub Actions - PR replies for modified files](https://github.com/microsoft/TypeScript/blob/main/.github/workflows/pr-modified-files.yml)
7 | - https://github.com/microsoft/typescript-bot-test-triggerer -- runs on the Azure Function typescriptbot-github, see [[Triggering TypeScript Bot]] -- responds to "test this" messages from team members.
8 | - https://github.com/microsoft/Typescript-repos-automation -- runs on the Azure Function TypeScriptReposAutomation -- more simple reactions to labels.
9 | - https://github.com/microsoft/TypeScript-Twoslash-Repro-Action -- run `tsrepro` and bisects: https://github.com/microsoft/TypeScript/blob/main/.github/workflows/twoslash-repros.yaml
10 | - https://github.com/microsoft/typescript-error-deltas -- produces PR comments showing new errors caused by PRs
11 | - https://github.com/microsoft/typescript-benchmarking -- produces PR comments showing benchmark results
12 |
13 | ## Definitely Typed repo
14 |
15 | - https://github.com/DefinitelyTyped/dt-mergebot -- runs on the Azure Function DTMergebot -- posts status comments, adds labels, maintains board, merges PRs.
16 | - https://github.com/microsoft/DefinitelyTyped-tools -- runs the publisher on GitHub Actions
17 | - [DangerBotOSS](https://github.com/definitelytyped/definitelytyped/tree/main/.github/workflows/CI.yml) -- suggests missed exports (posts as DangerBotOSS, not typescript-bot)
18 |
--------------------------------------------------------------------------------
/Architectural-Overview.md:
--------------------------------------------------------------------------------
1 | ## Layer Overview
2 | ## Data Structures
3 |
4 | Moved to [the glossary](https://github.com/microsoft/TypeScript-Compiler-Notes/blob/main/GLOSSARY.md) of the compiler-notes repo.
5 |
6 | ## Overview of the compilation process
7 |
8 | Moved to the root readme of the [compiler-notes repo](https://github.com/microsoft/TypeScript-Compiler-Notes).
9 |
10 | ## Terminology
11 |
12 | ### **Full Start/Token Start**
13 | ### **Trivia**
14 |
15 | See [the Scanner](https://github.com/microsoft/TypeScript-Compiler-Notes/blob/main/codebase/src/compiler/scanner.md) in the compiler-notes repo.
--------------------------------------------------------------------------------
/Blog-Post-Ideas.md:
--------------------------------------------------------------------------------
1 | **How-to guides for non-language features**
2 |
3 | * Use the npm package for xcopyable build scripts
4 | * Use the watch flag for faster development
5 | * Manage ///reference hell; keep files in correct order when using --out
6 | * Combine external modules with browserify
7 | * Use Angular with TypeScript
8 | * Use knockout with TypeScript
9 | * Use […] with TypeScript
10 | * Guest blog: basarat explains grunt-ts
11 | * Use .d.ts files for separate compilation
12 | * How to use TypeScript with Sublime/Emacs/etc
13 | * Common workflows with linters (JS and TS), minifiers, etc
14 |
15 | **Explorations**
16 |
17 | * Type inference in TypeScript (multi-part series)
18 | * Object serialization in TypeScript (revivers for class prototypes, etc)
19 |
20 | **Deep dives (handbook updates?)**
21 |
22 | * Function overloading
23 | * Classes
24 | * Modules
25 | * Enum and const enum
26 | * Let and const
27 |
28 | **Why and How?**
29 |
30 | * Why are function parameter types bivariant?
31 | * How do I handle `this` in my program?
32 | * When should I use instance methods vs prototype methods?
33 | * How do I write a definition file? Walk through an example
34 | * Advanced version: Choosing between overloads/optional params, use `{}` instead of `any`, etc
35 | * How do I convert a JavaScript file to TypeScript? Walk through an example
36 | * Advanced performance optimizations for rest and optional arguments
37 |
38 | **Well-intentioned C# programmers**
39 |
40 | * Why can’t I declare an arbitrary indexer?
41 | * What’s the deal with `typeof T` ?
42 | * How do I do reflection?
43 |
--------------------------------------------------------------------------------
/Cancellation-Support-in-tsserver.md:
--------------------------------------------------------------------------------
1 | This page has moved to https://github.com/Microsoft/TypeScript/wiki/Standalone-Server-%28tsserver%29#cancellation
--------------------------------------------------------------------------------
/Coding-guidelines.md:
--------------------------------------------------------------------------------
1 | # ***STOP READING IMMEDIATELY***
2 |
3 | ## THIS PAGE PROBABLY DOES **NOT** PERTAIN TO YOU.
4 |
5 | These are Coding Guidelines for ***Contributors to TypeScript***.
6 | This is ***NOT*** a prescriptive guideline for the TypeScript community.
7 | These guidelines are meant for **contributors to the TypeScript project's codebase**.
8 | We have chosen many of them for team consistency. Feel free to adopt them for your own team. \
9 | \
10 | AGAIN: This is ***NOT*** a prescriptive guideline for the TypeScript community
11 | --------------------
12 |
13 | ## **Please do not file issues about these guidelines.**
14 |
15 | ## Names
16 |
17 | 1. Use PascalCase for type names.
18 | 2. Do not use `I` as a prefix for interface names.
19 | 3. Use PascalCase for enum values.
20 | 4. Use camelCase for function names.
21 | 5. Use camelCase for property names and local variables.
22 | 6. Do not use `_` as a prefix for private properties.
23 | 7. Use whole words in names when possible.
24 |
25 | ## Components
26 | 1. 1 file per logical component (e.g. parser, scanner, emitter, checker).
27 | 2. Do not add new files. :)
28 | 3. files with `.generated.*` suffix are auto-generated, do not hand-edit them.
29 |
30 | ## Types
31 | 1. Do not export types/functions unless you need to share it across multiple components.
32 | 2. Do not introduce new types/values to the global namespace.
33 | 3. Shared types should be defined in `types.ts`.
34 | 4. Within a file, type definitions should come first.
35 |
36 | ## `null` and `undefined`
37 | 1. Use `undefined`. Do not use null.
38 |
39 | ## General Assumptions
40 | 1. Consider objects like Nodes, Symbols, etc. as immutable outside the component that created them. Do not change them.
41 | 2. Consider arrays as immutable by default after creation.
42 |
43 | ## Classes
44 | 1. For consistency, do not use classes in the core compiler pipeline. Use function closures instead.
45 |
46 | ## Flags
47 | 1. More than 2 related Boolean properties on a type should be turned into a flag.
48 |
49 | ## Comments
50 | 1. Use JSDoc style comments for functions, interfaces, enums, and classes.
51 |
52 | ## Strings
53 | 1. Use double quotes for strings.
54 | 2. All strings visible to the user need to be localized (make an entry in diagnosticMessages.json).
55 |
56 | ## Diagnostic Messages
57 | 1. Use a period at the end of a sentence.
58 | 2. Use indefinite articles for indefinite entities.
59 | 3. Definite entities should be named (this is for a variable name, type name, etc..).
60 | 4. When stating a rule, the subject should be in the singular (e.g. "An external module cannot..." instead of "External modules cannot...").
61 | 5. Use present tense.
62 |
63 | ## Diagnostic Message Codes
64 | Diagnostics are categorized into general ranges. If adding a new diagnostic message, use the first integral number greater than the last used number in the appropriate range.
65 | * 1000 range for syntactic messages
66 | * 2000 for semantic messages
67 | * 4000 for declaration emit messages
68 | * 5000 for compiler options messages
69 | * 6000 for command line compiler messages
70 | * 7000 for noImplicitAny messages
71 |
72 | ## General Constructs
73 |
74 | For a variety of reasons, we avoid certain constructs, and use some of our own. Among them:
75 |
76 | 1. Do not use `for..in` statements; instead, use `ts.forEach`, `ts.forEachKey` and `ts.forEachValue`. Be aware of their slightly different semantics.
77 | 2. Try to use `ts.forEach`, `ts.map`, and `ts.filter` instead of loops when it is not strongly inconvenient.
78 |
79 | ## Style
80 |
81 | 1. Use arrow functions over anonymous function expressions.
82 | 2. Only surround arrow function parameters when necessary.
For example, `(x) => x + x` is wrong but the following are correct:
83 | - `x => x + x`
84 | - `(x,y) => x + y`
85 | - `(x: T, y: T) => x === y`
86 | 3. Always surround loop and conditional bodies with curly braces. Statements on the same line are allowed to omit braces.
87 | 4. Open curly braces always go on the same line as whatever necessitates them.
88 | 5. Parenthesized constructs should have no surrounding whitespace.
A single space follows commas, colons, and semicolons in those constructs. For example:
89 | - `for (var i = 0, n = str.length; i < 10; i++) { }`
90 | - `if (x < 10) { }`
91 | - `function f(x: number, y: string): void { }`
92 | 6. Use a single declaration per variable statement
(i.e. use `var x = 1; var y = 2;` over `var x = 1, y = 2;`).
93 | 7. `else` goes on a separate line from the closing curly brace.
94 | 8. Use 4 spaces per indentation.
95 |
--------------------------------------------------------------------------------
/Common-Errors.md:
--------------------------------------------------------------------------------
1 | Deprecated doc
--------------------------------------------------------------------------------
/Compiler-Internals.md:
--------------------------------------------------------------------------------
1 | > ### This page has moved to https://github.com/microsoft/TypeScript-Compiler-Notes/
--------------------------------------------------------------------------------
/Compiler-Options.md:
--------------------------------------------------------------------------------
1 | > ### This page has moved to http://www.typescriptlang.org/docs/handbook/compiler-options.html
--------------------------------------------------------------------------------
/Configuring-MSBuild-projects-to-use-NuGet.md:
--------------------------------------------------------------------------------
1 | > **Note**: The install script will remove the default import to the `Microsoft.TypeScript.targets` file;
2 | if you have manually edited the import before, you will need to remove it yourself **before** proceeding.
3 | See [Removing default imports](#removing-default-imports) for more details.
4 |
5 | > **Note**: The Nuget package depends on the x86 version of [Visual C++ Redistributable for Visual Studio 2015]
6 | (https://www.microsoft.com/en-us/download/details.aspx?id=48145).
7 | This is generally already installed on your computer, but you can verify that within **Programs and Features**.
8 |
9 | ## For major releases (https://www.nuget.org)
10 |
11 | * Right-Click -> Manage NuGet Packages
12 | * Search for `Microsoft.TypeScript.MSBuild`
13 | 
14 |
15 | * Hit `Install`
16 | * When install is complete, rebuild!
17 |
18 |
19 | ## For Nightly drops (https://www.myget.org)
20 |
21 | 1. Add a new Package Source
22 | * Go to `Tools` -> `Options` -> `NuGet Package Manager` -> `Package Sources`
23 | * Create a new Source:
24 | * Name: `TypeScript Nightly`
25 | * Source: `https://www.myget.org/F/typescript-preview/`
26 | 
27 |
28 | 2. Use the new Package Source
29 | * On Project node Right-Click -> `Manage NuGet Packages`
30 | * Search for `Microsoft.TypeScript.MSBuild`
31 | 
32 | * Hit `Install`
33 | * When install is complete, rebuild!
34 |
35 |
36 | ## Removing default imports
37 |
38 | * Right-Click -> `Unload Project`
39 | * Right-Click -> `Edit `
40 | * Remove references to
41 |
42 | * `Microsoft.TypeScript.Default.props`
43 |
44 | The import should look something like:
45 |
46 | ```XML
47 |
50 | ```
51 |
52 | * `Microsoft.TypeScript.targets`
53 |
54 | The import should look something like:
55 |
56 | ```XML
57 |
60 | ```
61 |
--------------------------------------------------------------------------------
/Contributing-to-TypeScript.md:
--------------------------------------------------------------------------------
1 | There are three great ways to contribute to the TypeScript project: logging bugs, submitting pull requests, and creating suggestions.
2 |
3 | ### Logging Bugs
4 |
5 | To log a bug, just use the GitHub issue tracker. Confirmed bugs will be labelled with the `Bug` label. Please include code to reproduce the issue and a description of what you expected to happen.
6 |
7 | ### Pull Requests
8 |
9 | Before we can accept a pull request from you, you'll need to sign the Contributor License Agreement (CLA). See the "Legal" section of the [CONTRIBUTING.md guide](https://github.com/Microsoft/TypeScript/blob/main/CONTRIBUTING.md). That document also outlines the technical nuts and bolts of submitting a pull request. Be sure to follow our [[Coding Guidelines|coding-guidelines]].
10 |
11 | You can learn more about the compiler's codebase at https://github.com/microsoft/TypeScript-Compiler-Notes/
12 |
13 | ### Suggestions
14 |
15 | We're also interested in your feedback in future of TypeScript. You can submit a suggestion or feature request through the issue tracker. To make this process more effective, we're asking that these include more information to help define them more clearly. Start by reading the [[TypeScript Design Goals]] and refer to [[Writing Good Design Proposals]] for information on how to write great feature proposals.
16 |
17 | ### Issue Tracking 101
18 |
19 | Unlabelled issues haven't been looked at by a TypeScript coordinator. You can expect to see them labelled within a few days of being logged.
20 |
21 | Issues with the `Bug` label are considered to be defects. Once they have the `Bug` label, they'll either be assigned to a TypeScript developer and assigned a milestone, or put in the Community milestone, indicating that we're accepting pull requests for this bug. Community bugs are a great place to start if you're interested in making a code contribution to TypeScript.
22 |
23 | We'll be using Labels to track the status of suggestions or feature requests. You can expect to see the following:
24 | * `Suggestion`: We consider this issue to not be a bug per se, but rather a design change or feature of some sort. Any issue with this label should have at least one more label from the list below
25 | * `Needs Proposal`: A full write-up is needed to explain how the feature should work
26 | * `Needs More Info`: A proposal exists, but there are follow-up questions that need to be addressed
27 | * `In Discussion`: This is being discussed by the TypeScript design team. You can expect this phase to take at least a few weeks, depending on our schedule
28 | * `Ready to Implement`: The proposal is accepted and has been designed enough that it can be implemented now
29 | * `help wanted`: We are accepting pull requests that fully implement this feature
30 | * `Committed`: We have allocated time on the team schedule to implement this feature
31 |
32 | Declined suggestions will have the `Declined` label along with one of the following:
33 | * `Out of Scope`: Is outside the scope of the TypeScript compiler; would be better implemented as a separate tool or extension rather than a change to TypeScript itself
34 | * `Too Complex`: The amount of complexity that this (and its future implications) would introduce is not justified by the amount of value it adds to the language
35 | * `Breaking Change`: Would meaningfully break compatibility with JavaScript or a previous version of TypeScript, or would prevent us from implementing known future ECMAScript proposals
36 | * `By Design`: This aspect of the language is an intentional design decision
37 |
38 | Issues that are not bugs or suggestions will be labelled appropriately (`Question`, `By Design`, `External`) and closed. Please use [Stack Overflow](http://stackoverflow.com/questions/tagged/typescript) for TypeScript questions.
39 |
40 | ### Discussion
41 |
42 | In order to keep the conversation clear and transparent, limit discussion to English and keep things on topic with the issue.
43 | Be considerate to others and try to be courteous and professional at all times.
44 |
45 | ### Documentation
46 |
47 | For any new features, please:
48 | * Add a link to the Roadmap: https://github.com/Microsoft/TypeScript/wiki/Roadmap
49 | * Add a blurb to what's new page: https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript
50 | * Add a section to the Handbook, if big enough: https://github.com/Microsoft/TypeScript-Handbook
51 | * For breaking changes:
52 | * Add a breaking change notice: https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes
53 | * or to the API breaking changes pages: https://github.com/Microsoft/TypeScript/wiki/API-Breaking-Changes
54 |
--------------------------------------------------------------------------------
/Debugging-Language-Service-in-VS-Code.md:
--------------------------------------------------------------------------------
1 | VS Code is designed around an extension model. TypeScript provides a server called TSServer that provides information which supports quick-info, completions, etc., then VS Code acts as a client which queries the server when this information is needed.
2 |
3 | For example, VS Code queries TSServer for quick-info when the user's mouse hovers over a variable by sending a message to TSServer. TSServer will respond with information such as the appropriate type, and the styling to apply to the text that describes the type.
4 |
5 | Organizationally, the client-side code for communicating with the TypeScript server lives in [`extensions/typescript-language-features`](https://github.com/Microsoft/vscode/tree/master/extensions/typescript-language-features) in [the VS Code repository](https://github.com/Microsoft/vscode).1
6 |
7 | Meanwhile, the server-side code lives in `src/services` and `src/server` of [the TypeScript repository](https://github.com/Microsoft/TypeScript).
8 |
9 | ## Using stable VS Code to Debug Stable TSServer
10 |
11 | There are two steps to this:
12 |
13 | - Launch VS Code with an extra environment variable, and different user profile.
14 | - Connect to this VS Code's TSServer.
15 |
16 | To launch VS Code with a different profile and a debug copy of TSServer:
17 |
18 | ```sh
19 | # Sets the TSServer port to 5667, this can be any number
20 | # Sets the user-data directory to be ~/.vscode-debug/ instead of ~/.vscode/
21 |
22 | TSS_DEBUG=5667 code --user-data-dir ~/.vscode-debug/
23 | ```
24 |
25 | This will open VS Code as a separate app from your current one, it may have some of your extensions but not your settings. As long as you consistently use the above command, then you can save settings for debugging between sessions.
26 |
27 | Optionally you can use `TSS_DEBUG_BRK` (i.e. `TSS_DEBUG_BRK=5567`) to have the TSServer wait for your debugger before launching.
28 |
29 | This will launch a debug TSServer which you can connect to from inside the TypeScript codebase. Open up the TypeScript codebase, and look at the debugging panel. At the top, look to see if there is a drop-down item for debugging by Attaching to VS Code TSServer then select that.
30 |
31 | If there isn't, copy the template of `.vscode/launch.template.json` to `.vscode/launch.json` and it should show up.
32 |
33 | Select the "Attach by ..." option in the dropdown for debugging and hit the play button, it will ask you to choose a node instance to connect to. In the above example we used the port 5667, look for that and select it.
34 |
35 | That should have you connected to the TSServer for the debugging app version of VS Code while you work in the production version.
36 |
37 | ## Using Stable VS Code with Development TSServer
38 |
39 |
40 | VS Code chooses where to launch TSServer from via the setting: `typescript.tsdk`. Continuing from above, if you want to have your TSServer use a local copy of TypeScript then change this setting (in `.vscode/settings.json` or your user JSON settings) to:
41 |
42 | ```json
43 | {
44 | "typescript.tsdk": "/path/to/repo/TypeScript/built/local"
45 | }
46 | ```
47 |
48 | This version of TypeScript may not be selected automatically; ensure that the above is being used by running the "TypeScript: Select TypeScript Version..." command in the command palette (Ctrl+Shift+P or Cmd+Shift+P).
49 |
50 | This is probably enough for most contributors, but if you are doing heavy duty VS Code and TypeScript work, you may want to carry on.
51 |
52 | ---
53 |
54 | ## Development VS Code with Development TSServer
55 |
56 | We will use a stable version of VS Code to debug a development version of VS Code running against a development version of TSServer.
57 |
58 | 1. Download/install a stable version of vs code.
59 | 2. Follow the instructions to [setup a development version of VS Code](https://github.com/Microsoft/vscode/wiki/How-to-Contribute).2
60 | 3. Clone the TypeScript repo locally, and follow the instructions on [building TypeScript](https://github.com/Microsoft/TypeScript#building).
61 | 4. [Update the User Settings](https://code.visualstudio.com/docs/languages/typescript#_using-newer-typescript-versions) in the development version of VS Code, to point to the `built/local` directory of your local TypeScript repository.
62 |
63 | This will look something like the following:
64 |
65 | ```json
66 | {
67 | "typescript.tsdk": "/path/to/repo/TypeScript/built/local"
68 | }
69 | ```
70 |
71 | You may instead update this in the Workspace Settings for a project as well, but you will have to remember that the development version of TSServer will only be in effect within that project.
72 |
73 | From here, there are different steps for debugging the client- and server-side, respectively.
74 |
75 | ## Debugging tsserver (server-side)
76 |
77 | 1. Choose an available port to debug TSServer using either of the following two methods (in the rest of this guide, we assume you chose 5859):
78 | * In a shell, export the `TSS_DEBUG` environment variable to an open port. We will run the development VS Code instance from within that shell.
79 |
80 | For most Unix-like shells (e.g. bash), this will be something like
81 |
82 | ```sh
83 | export TSS_DEBUG=5859
84 | ```
85 |
86 | For PowerShell, this is something like
87 |
88 | ```posh
89 | $env:TSS_DEBUG = 5859
90 | ```
91 |
92 | * Alternatively, manually edit `extensions/typescript/src/typescriptServiceClient.ts` in your development-side VS Code, setting the port to an open one.
93 |
94 | 2. Update `launch.json` with an option to attach to the node instance, with sourcemaps from your `built/local` folder.
95 |
96 | For VS Code v1.13.1+ and Node v8.0+, your `launch.json` might look like the following:
97 |
98 | ```json5
99 | {
100 | "version": "0.2.0",
101 | "configurations": [
102 | // Other configs
103 | {
104 | "name": "Attach to TS Server",
105 | "type": "node",
106 | "request": "attach",
107 | "protocol": "inspector",
108 | "port": 5859,
109 | "sourceMaps": true,
110 | "outFiles": ["/path/to/repo/TypeScript/built/local"],
111 | }
112 | ]
113 | }
114 | ```
115 |
116 | For the same versions of Code, but older versions of Node (e.g. 6.x), you'll need to set `"protocol"` to be `"legacy"`.
117 |
118 | 3. Launch an instance of your development VS Code, and open a TypeScript file.
119 | 4. Launch your stable-release version of VS Code.
120 | 5. Attach the stable VS Code instance to the development instance.
121 |
122 | ## Debugging the Extension Host (client-side)
123 |
124 | 3) Launch an instance of development vs code.
125 |
126 | 4) Launch an instance of stable vs code.
127 |
128 | 5) Attach the stable vs code instance to the development instance.
129 |
130 |
131 | ---
132 | 1 In particular, the built-in extension spawns the node instance that loads tsserver via the call to electron.fork() in `extensions/typescript/src/typescriptServiceClient.ts`.
133 |
134 | 2 If you are on Linux, be sure to increase the number of file watchers per the fix for ENOSPC [errors](https://github.com/Microsoft/vscode/wiki/How-to-Contribute#incremental-build). for opening medium-large projects like Typescript, the default limit of 8192 is almost certainly too small.
135 |
--------------------------------------------------------------------------------
/FAQs-for-API-Consumers.md:
--------------------------------------------------------------------------------
1 | #### Frequently asked Questions
2 | * [What are these `rescanFooToken` functions in the scanner for?](#what-are-these-rescanfootoken-functions-in-the-scanner-for)
3 | * [Why does the lexical classifier sometimes give inaccurate results for nested template strings?](#why-does-the-lexical-classifier-sometimes-give-inaccurate-results-for-nested-template-strings)
4 |
5 | =================
6 |
7 | ### What are these `rescanFooToken` functions in the scanner for?
8 |
9 | The ECMASCript grammar describes *lexical goals* for its grammar, for which an alternate scanning rule should be used in its place from the default. These rules are triggered when ***syntactically aware consumers*** require them (i.e. ECMAScript parsers which know when a construct can occur). For details, [see the current ES spec](https://tc39.github.io/ecma262/#sec-ecmascript-language-lexical-grammar).
10 |
11 | One example of this is for a single `/` (the forward-slash token). As long as the `/` isn't immediately followed by another `/` (indicating a comment), the default goal (*InputElementDiv*) is to scan it as a plain `/` or `/=` (for division operations); however, in contexts where a bare `/` or `/=` would not make sense (such as when parsing a *PrimaryExpression*), the goal is modified to *InputElementRegExp* to scan out a regular expression literal.
12 |
13 | The rescan functions roughly correspond to triggering the alternate rules, though rather than passing an extra parameter, a rescan is demanded of the scanner.
14 |
15 | Though lexical goals are not addressed in the TypeScript spec, there is effectively one new rule added for the `>`s (greater-than characters) to make generics easy to parse, but impose that any places which might encounter a `>>`, `>>>`, etc. require a rescan.
16 |
17 | =================
18 |
19 | ### Why does the lexical classifier sometimes give inaccurate results for nested template strings?
20 |
21 | Template strings did not even originally have lexical classification support prior to 1.5 for [several technical reasons](https://github.com/Microsoft/TypeScript/issues/1477#issuecomment-66907946). However, due to demand, [support was added for what we believed would be the majority of practical uses](https://github.com/Microsoft/TypeScript/pull/2026).
22 |
23 | As a precursor, when discussing template expressions, it is useful to be familiar with the following syntactic components:
24 |
25 | Syntax Kind | Example
26 | ------|------------
27 | `NoSubstitutionTemplateLiteral` | `` `Hello world` ``
28 | `TemplateHead` | `` `abc ${ ``
29 | `TemplateMiddle` | `} def ${ `
30 | `TemplateTail` | `` } ghi ` ``
31 | `TemplateExpression` | `` `abc ${ 0 } def ${ 1 } ghi ` ``
32 |
33 | The lexical classifier is a rudimentary classifier that is intended to be fast and work on single lines at a time. It works through augmenting TypeScript's scanner, which itself works on a regular language grammar except when given a lexical goal in mind. Keep in mind, lexical goals can only be triggered accurately when motivated by a syntactically aware entity, while the lexical classifier only has the context of a single line with a previous line state to work with.
34 |
35 | To throw a wrench in the gears, substitution templates are not regular (they are context-free, and if someone wants to write a formal proof of this, *a la* [Rust's string literals not being context-free][rust], feel free to send a [pumping lemma][] pull request for the wiki). The issue is that a `}` (close curly brace) and the template tail literals (`}...${` (*TemplateMiddle*) and ``}...${` `` (*TemplateTail*)) are need to be distinguished by lexical goals, which are triggered by ***syntactically aware*** consumers.
36 |
37 | [rust]: https://github.com/rust-lang/rust/blob/master/src/grammar/raw-string-literal-ambiguity.md
38 | [pumping lemma]: https://en.wikipedia.org/wiki/Pumping_lemma_for_regular_languages "Pumping lemma for regular languages"
39 |
40 | The basic solution is to just maintain a stack. However, in the interest of giving accurate results without complicating the classifier too much, we only keep track of whether a *single* template expression was unterminated. This means that if you have `` `...${ `...${ `` (two *TemplateHead*s) on a single line, or a multiline object literal in substitution position, your results may not be accurate. In practice this does not happen much, so the behavior is largely acceptable.
41 |
42 | In any case, consumers who need classifiers should rely on the syntactic (and semantic) classifiers if accuracy is important, using the lexical classifier as a fallback.
43 |
--------------------------------------------------------------------------------
/Getting-logs-from-TS-Server-in-VS-Code.md:
--------------------------------------------------------------------------------
1 | The TS Server is a Node process which editors talk to in order to provide rich functionality for your TypeScript/JavaScript code (e.g. auto-completions, go-to-definition, quick fixes, refactorings).
2 |
3 | This page describes how to get a TS Server log within Visual Studio Code. You might need this to diagnose why a crash is taking place (often forcing you to restart VS Code or the JS/TS language server), or to make sure that the communication between TypeScript the language and your editor is what you expect.
4 |
5 | 1. Open the project you want to investigate in Visual Studio Code.
6 | 1. Run the command `Open TS Server Log` (You can run commands with `View` > `Command Palette`).
7 | 1. This command should offer to turn on logging if you don't have it enabled. Enable logging if it isn't already.
8 | 1. Restart your project, and try to only do the reproduction case.
9 | 1. Run `Open TS Server Log` again and it will re-direct you to a file with the logs.
10 |
11 | The log should start like:
12 |
13 | ```
14 | Info 0 [13:5:26.815] Starting TS Server
15 | Info 1 [13:5:26.816] Version: 3.7.0-dev.20190922
16 | Info 2 [13:5:26.816] Arguments: /Applications/Visual Studio Code - Insiders.app/Contents/Frameworks/Code - Insiders Helper.app/Contents/MacOS/Code - Insiders Helper /Users/ortatherox/dev/typescript/TypeScript/node_modules/typescript/lib/tsserver.js --useInferredProjectPerProjectRoot --enableTelemetry --cancellationPipeName /var/folders/3d/j0zt8n5d77n_4mthj6nsb6h00000gn/T/vscode-typescript501/58d39090e29f4276f14f/tscancellation-e9842eb530b8e993176a.tmp* --logVerbosity verbose --logFile /Users/ortatherox/Library/Application Support/Code - Insiders/logs/20191014T045453/exthost13/vscode.typescript-language-features/tsserver-log-w6HewS/tsserver.log --globalPlugins typescript-tslint-plugin --pluginProbeLocations /Users/ortatherox/.vscode-insiders/extensions/ms-vscode.vscode-typescript-tslint-plugin-1.2.2 --locale en --noGetErrOnBackgroundUpdate --validateDefaultNpmLocation
17 | ```
18 |
19 | This log will contain file paths about the current project, and where your VS Code application is. If it's important to you, you may want to sanitize the log before sending it.
20 |
21 | If the log is pretty small, you can embed it directly into an issue comment. If it's very long, we recommend you paste it into a gist at https://gist.github.com and link to that. If privacy is still a concern, we may be able to discuss a more private exchange of logs.
22 |
23 | # Remember to Delete Your Old Logs
24 |
25 | Over time, especially as editing sessions can span multiple days, your TS Server logs might start to accumulate. While we are investigating a lightweight way to avoid saving these files to disk all the time, it can be helpful to recover space by deleting your logs periodically.
--------------------------------------------------------------------------------
/Home.md:
--------------------------------------------------------------------------------
1 | The TypeScript Wiki is for people who are interested in:
2 |
3 | - Debugging TypeScript problems: [Performance](https://github.com/microsoft/TypeScript/wiki/Performance), [Tracing](https://github.com/microsoft/TypeScript/wiki/Performance-Tracing), [Debugging](https://github.com/microsoft/TypeScript/wiki/Debugging-Language-Service-in-VS-Code)
4 | - [Using the compiler API](https://github.com/microsoft/TypeScript/wiki/Using-the-Compiler-API)
5 | - [Wanting to contribute to the TypeScript codebase or to understand the compiler](https://github.com/microsoft/TypeScript/wiki/Contributing-to-TypeScript)
6 |
7 | It is also used as a scratch-pad for one-off links which are useful when triaging GitHub issues. For example the [[FAQ]]
8 |
9 | If you are after documentation on how to use TypeScript the language, or the build tool: please see: https://www.typescriptlang.org
10 |
--------------------------------------------------------------------------------
/How-the-User-Tests-Work.md:
--------------------------------------------------------------------------------
1 | There are two types of user tests: npm install and submodule.
2 |
3 | ## NPM Install Tests
4 |
5 | npm install tests have two purposes.
6 |
7 | 1. Test the user experience of a Typescript package.
8 | 2. Test compilation of a Javascript package without having to use submodules.
9 |
10 | These tests have at least a package.json and a tsconfig.json.
11 |
12 | In the Typescript-user case, there is also an index.ts that matches how the user is expected to use the library. However, today, most of these files are just `import x = require('x')`. This just makes sure that the typings exported by the project continue to work with new versions of Typescript, even if the authors aren't paying attention to new versions.
13 |
14 | In the Javascript-source case, the tsconfig.json points into the node_modules directory: `include: ['node_modules/x/src']` or something similar. Many Javascript projects ship their source or something close to it, and an npm install is **much** easier than a git submodule.
15 |
16 | # Submodule Tests
17 |
18 | Submodule tests let us test project source without needing to check in a copy to a repo that we own. This is better than our internal real-world code tests, because reproing errors is much easier: just clone the repo and run tsc. However, it requires an open source project that can build with a single call to tsc. That excludes modern Angular and many Microsoft-internal projects.
19 |
20 | Also you have to use submodules.
21 |
22 |
23 | # Pitfalls of submodules
24 |
25 | 1. They are submodules!
26 | 2. The submodule repo name needs to be the same as the containing directory name.
27 |
--------------------------------------------------------------------------------
/How-to-maintain-Definitely-Typed-tests.md:
--------------------------------------------------------------------------------
1 | The Definitely Typed tests test new versions of Typescript on every package on Definitely Typed.
2 | They do this two ways:
3 |
4 | 1. Overnight, [a scheduled run](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build?definitionId=8&_a=summary).
5 | 2. On-demand, [triggered by a request to the bot](Triggering-TypeScript-Bot).
6 |
7 | The on-demand test runs twice: once on `main` and once on a commit from a PR. It's intended to let a PR author see what *new* errors are introduced by their change.
8 | The overnight test runs on the latest commit on Typescript. It's intended to let the Typescript team know what will break in the next release.
9 |
10 | Maintaining the Definitely Typed tests boils down to noticing errors in the overnight run and fixing them.
11 | There are 3 causes of failures:
12 |
13 | 1. Typescript changed and broke packages in a bad way: File a bug on Typescript.
14 | 2. Typescript changed and broke packages in a good way: File a bug, and probably a PR, on the package.
15 | 3. The package changed and now breaks, perhaps only on `typescript@next`: File a bug, and maybe a PR, on the package.
16 |
17 | For packages on Definitely Typed, don't bother filing a bug.
18 | Nobody reads them anyway.
19 | Instead, if the break is a good one, fix the problem yourself and send a PR.
20 |
21 | For Typescript and other repos, while the bugs are being fixed, you can add the package names to [expectedFailures.txt in DefinitelyTyped-tools](https://github.com/microsoft/DefinitelyTyped-tools/blob/master/packages/dtslint-runner/expectedFailures.txt).
22 |
23 | ### Categories of breaks
24 |
25 | 1. Trivial re-ordering in `$ExpectType`, which uses textual equality. This is a good break.
26 | 2. Out of memory, usually when Typescript changes how much memory it uses. This is almost always a bad break.
27 | 3. Complex assignability change. This is usually a good break.
28 | 4. Untested types for package written in Javascript. This is usually a bad break, but requires a fix in the package, not Typescript.
29 | 3. [Those that from afar look like flies](https://en.wikipedia.org/wiki/The_Analytical_Language_of_John_Wilkins).
30 |
31 |
32 | ### Miscellanea
33 |
34 | (To be moved to better categories)
35 |
36 | - The DT tests test not only the packages on Definitely Typed, but their dependencies. As more packages ship their own types, it's become a valuable way to see what dependencies in the Typescript ecosystem will break.
37 | - The on-demand test is split across four machines; the overnight test is split across two.
38 | - You can sign up to be mailed an alert when the overnight run has a failure.
39 |
--------------------------------------------------------------------------------
/Integrating-with-Build-Tools.md:
--------------------------------------------------------------------------------
1 | > ### This page has moved to http://www.typescriptlang.org/docs/handbook/integrating-with-build-tools.html
--------------------------------------------------------------------------------
/JSDoc-support-in-JavaScript.md:
--------------------------------------------------------------------------------
1 | A comprehensive introduction to type checking JavaScript files with TypeScript can be found in the [official handbook](https://www.typescriptlang.org/docs/handbook/type-checking-javascript-files.html#supported-jsdoc).
2 |
--------------------------------------------------------------------------------
/JSX.md:
--------------------------------------------------------------------------------
1 | > ### This page has moved to http://www.typescriptlang.org/docs/handbook/jsx.html
--------------------------------------------------------------------------------
/Nightly-drops.md:
--------------------------------------------------------------------------------
1 | A nightly build from the [main](https://github.com/Microsoft/TypeScript/tree/main) branch is published nightly to NPM and NuGet. Here is how you can get it and use it with your tools.
2 |
3 | ## Using npm
4 |
5 | ```shell
6 | npm install -g typescript@next
7 | ```
8 |
9 | ## Using NuGet with MSBuild:
10 |
11 | > Note: You'll need to configure your project to use the NuGet packages. Please see [Configuring MSBuild projects to use NuGet](https://github.com/Microsoft/TypeScript/wiki/Configuring-MSBuild-projects-to-use-NuGet) for more information.
12 |
13 | The nightlies are available on https://www.myget.org/gallery/typescript-preview
14 |
15 | There are two packages:
16 |
17 | * `Microsoft.TypeScript.Compiler`: Tools only (`tsc.exe`, `lib.d.ts`, etc.) .
18 | * `Microsoft.TypeScript.MSBuild`: Tools as above, as well as MSBuild tasks and targets (`Microsoft.TypeScript.targets`, `Microsoft.TypeScript.Default.props`, etc.)
19 |
20 |
21 | ## Visual Studio Code
22 |
23 | 1. Install the npm package `npm install typescript@next`, to your local `node_modules` folder.
24 | 2. Update, `.vscode/settings.json` with the following:
25 |
26 | ```json
27 | "typescript.tsdk": "/node_modules/typescript/lib"
28 | ```
29 |
30 | ## Sublime Text
31 |
32 | 1. Install the npm package `npm install typescript@next`, to a local `node_modules` folder, then
33 | 2. Update the `Settings - User` file with the following:
34 |
35 | ```json
36 | "typescript_tsdk": "/node_modules/typescript/lib"
37 | ```
38 |
39 | More information is available at: https://github.com/Microsoft/TypeScript-Sublime-Plugin#installation
40 |
--------------------------------------------------------------------------------
/No-New-Utility-Types.md:
--------------------------------------------------------------------------------
1 | We do not add new "utility" types to the standard library.
2 |
3 | The existing global utility types you see (`Omit`, `Pick`, etc) are either required for declaration emit, or were written before this rule was put into place.
4 |
5 | The primary reason for this is that, for a given type, we need to:
6 | * Define its overall desired behavior
7 | * Pick a name that doesn't conflict with anything likely to be in userspace, but is still descriptive
8 | * Decide if they are distributive or not distributive
9 | * Decide if they should be strongly or weakly defined in terms of their constraints
10 | * Make many other type-specific decisions
11 |
12 | Reasonable people can disagree about any of these points, much as they do about other design decisions. For example, [the typing of `Array#includes` is "stricter" than some people would like](https://github.com/microsoft/TypeScript/issues/26255), whereas `Omit` is not [considered "strict enough" by some people](https://github.com/microsoft/TypeScript/issues/30825). Any time we've introduced a utility type, it's spurred these disatisfications where people feel that TypeScript obviously didn't just pick the "correct" definition, even though the definition we added matched someone else's "correct" definition. Even types you might think are easy to define, like `Nullable`, can and do get [different definitions by different people](https://github.com/microsoft/TypeScript/pull/51254/files). And in the event we change our minds and agree about which definition *should* have been used, it's too much of a breaking change to modify these types at all once they're in common use.
13 |
14 | Since there's no *need* for these utility types, and people rightfully are annoyed that any definition we pick will effectively prevent anyone else from using those names (due to confusion), our current stance is that it's better to leave utility type definition up to users so that they can pick the definitions that best match their individual desired semantics, rather than introducing a new global type that almost will certainly raise justifiable ire among a nontrivial set of users.
--------------------------------------------------------------------------------
/Node-Target-Mapping.md:
--------------------------------------------------------------------------------
1 | ## Recommended Node TSConfig settings
2 |
3 | You can let TypeScript compile as little as possible by knowing what the baseline support
4 | for ECMAScript features are available in your node version
5 |
6 | You can also use https://github.com/tsconfig/bases/ to find `tsconfig.json`s to extend, simplifying your own JSON files to just the options for your project.
7 |
8 | To update this file, you can use [node.green](https://node.green) to map to the different options in [microsoft/typescript@src/lib](https://github.com/Microsoft/TypeScript/tree/main/src/lib)
9 |
10 | #### Node 24
11 |
12 | ```json
13 | {
14 | "compilerOptions": {
15 | "lib": ["ES2024"],
16 | "module": "nodenext",
17 | "target": "ES2024"
18 | }
19 | }
20 | ```
21 |
22 | Note: [`module` is set to `nodenext` to allow `require("esm")`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-8.html#support-for-require-of-ecmascript-modules-in---module-nodenext). After TypeScript 5.9 is released, it is recommended to set it to `node20` instead.
23 |
24 | #### Node 22
25 |
26 | ```json
27 | {
28 | "compilerOptions": {
29 | "lib": ["ES2023"],
30 | "module": "nodenext",
31 | "target": "ES2023"
32 | }
33 | }
34 | ```
35 |
36 | Note: [`module` is set to `nodenext` to allow `require("esm")`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-8.html#support-for-require-of-ecmascript-modules-in---module-nodenext). After TypeScript 5.9 is released, it is recommended to set it to `node20` instead.
37 |
38 | #### Node 20
39 |
40 | ```json
41 | {
42 | "compilerOptions": {
43 | "lib": ["ES2023"],
44 | "module": "nodenext",
45 | "target": "ES2023"
46 | }
47 | }
48 | ```
49 |
50 | Note: [`module` is set to `nodenext` to allow `require("esm")`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-8.html#support-for-require-of-ecmascript-modules-in---module-nodenext). After TypeScript 5.9 is released, it is recommended to set it to `node20` instead.
51 |
52 | #### Node 18
53 |
54 | ```json
55 | {
56 | "compilerOptions": {
57 | "lib": ["ES2022"],
58 | "module": "node16",
59 | "target": "ES2022"
60 | }
61 | }
62 | ```
63 |
64 | #### Node 16
65 |
66 | ```json
67 | {
68 | "compilerOptions": {
69 | "lib": ["ES2021"],
70 | "module": "node16",
71 | "target": "ES2021"
72 | }
73 | }
74 | ```
75 |
76 | Note: Due to a V8 bug, one rarely-used ES2020 feature was incorrectly implemented in Node <16.3.0 - "spread parameters after optional chaining"; see [issue 46325](https://github.com/microsoft/TypeScript/issues/46325). If you use this feature and need to support versions of Node before 16.3.0, you may need to drop `target` to `ES2019`.
77 |
78 | #### Node 14
79 |
80 | ```json
81 | {
82 | "compilerOptions": {
83 | "lib": ["ES2020"],
84 | "module": "node16",
85 | "target": "ES2020"
86 | }
87 | }
88 | ```
89 |
90 | Note: Due to a V8 bug, one rarely-used ES2020 feature was incorrectly implemented in all releases of Node 14 - "spread parameters after optional chaining"; see [issue 46325](https://github.com/microsoft/TypeScript/issues/46325). If you use this feature, you may need to drop `target` to `ES2019`.
91 |
92 | #### Node 12
93 |
94 | ```json
95 | {
96 | "compilerOptions": {
97 | "lib": ["ES2019"],
98 | "module": "node16",
99 | "target": "ES2019"
100 | }
101 | }
102 | ```
103 |
104 | #### Node 10
105 |
106 | ```json
107 | {
108 | "compilerOptions": {
109 | "lib": ["es2018"],
110 | "module": "commonjs",
111 | "target": "es2018"
112 | }
113 | }
114 | ```
115 |
116 | #### Node 8
117 |
118 | ```json
119 | {
120 | "compilerOptions": {
121 | "lib": ["es2017"],
122 | "module": "commonjs",
123 | "target": "es2017"
124 | }
125 | }
126 | ```
127 |
128 |
--------------------------------------------------------------------------------
/Preferred-Issue-Titles.md:
--------------------------------------------------------------------------------
1 | # Examples of Good Issue Titles
2 |
3 | * No error issued when supertype is used in place of subtype
4 | * Incorrect error issued when using class where expression is expected
5 | * Poor error message when comparing string literal types
6 | * Incorrect type inferred to initialized class property
7 | * Incorrect formatting with array of object literals
8 | * Missing member in completion list on 'this' in interface when base type is intersection type
9 | * Suggestion: Don't issue errors when modules aren't resolved
10 | * Property of union type not narrowed in 'else' block
11 | * Inferred type of default export is missing index signature
12 | * Crash when accessing property declared in JSDoc
13 | * Comments missing in emit for switch block
14 |
15 | # Examples of Unacceptable Issue Titles
16 |
17 | * Can't use jquery with angular
18 | * Unexpected type message
19 | * Compiler throws wrong error
--------------------------------------------------------------------------------
/Providing-Visual-Studio-Repro-Steps.md:
--------------------------------------------------------------------------------
1 | Due to the complexity of Visual Studio and the variety of projects you can write in it, simple screenshots or text descriptions are often not enough for us (the developers who work on Visual Studio) to be able to address a problem. We need to be able to reliably reproduce a problem first in order to understand what the issue is, and second to ensure that the fixes we provide fully address the problem.
2 |
3 | This document is a guide to how to provide repro steps when you encounter a problem in Visual Studio. We provide here many different options, listed in *preference* order - please try to provide the first listed option that you are able to.
4 |
5 | In addition to the data provided below, we always want to know the exact version of Visual Studio (including updates) that you have installed, what OS you're using, and any other configuration data that might be relevant to the problem at hand. Much of this information is provided during the Feedback Upload process, but listing it explicitly can also help other users confirm the issue and is always a good practice.
6 |
7 | ## Steps in a New Project
8 |
9 | The very best thing we can work with is also the simplest: If you can describe how to reproduce a problem by simply starting from one of the built-in project templates, that is often ideal.
10 |
11 | Many project templates have similar names - be *extremely* specific! Saying "new web app" might refer to any of several dozen different templates; provide their *full names* with descriptions - "ASP.net Core Web Application, then choose the Blank template on the following dialog".
12 |
13 | If you're using a template you installed from the web or gallery, we would prefer that you provide a zip file (see below). Matching the exact version of a template you may have downloaded months ago is very difficult and may not produce the same behavior.
14 |
15 | ## A Zip File
16 |
17 | If you're not sure how to reproduce the problem from a fresh project, a zip file containing your entire solution folder is often the next best thing. A Microsoft employee will provide you an email address to send it to, and we'll work with you 1:1 to determine what the issue is.
18 |
19 | #### Sidebar: NDAs and Confidentiality
20 |
21 | Keeping the security and confidentiality of your code is absolutely critical to us. You can be assured that the contents and nature of any files you send will *not* be disclosed in any way. We will delete these files as soon as possible, and our interaction with your files will be kept to the minimum required to diagnose the underlying issue.
22 |
23 | If your organization requires the signing of a Non-disclosure Agreement (NDA), in most cases we will be able to sign such an NDA to facilitate debugging an issue. Please follow up via email with the provided engineer and they will be able to provide more details.
24 |
25 | #### Anonymization / Simplification
26 |
27 | If the content and names of your files are irrelevant to the issue at hand, a simplified/cleansed version of the above zip file is also very much acceptable. The smallest and simplest zip file that can reproduce the problem is always preferred - if you *can* send us a single project out of your solution that still reliably demonstrates the issue, we'd prefer it over a larger one.
28 |
29 | ## A File Listing
30 |
31 | If you're unable to provide a zip file, a file listing can be useful. This **PowerShell** command will produce a `files.csv` file listing the file names and lengths under a folder (replace `C:\MY_PROJECT` as needed):
32 |
33 | > `Get-ChildItem C:\MY_PROJECT -Recurse -Depth 5 | Where {!$_.PSIsContainer -or !$_.Attributes -match "ReparsePoint"} | Select-Object FullName, Length | Export-Csv -noTypeInformation -path files.csv`
34 |
35 | As above, you can post this in the issue comments, or send us the information in an email.
36 |
37 | A file listing is usually not enough information without a TypeScript Server log (see below).
38 |
39 | ## TypeScript Server Log
40 |
41 | For issues involving TypeScript or JavaScript language service issues, a TypeScript Server log is extremely useful in diagnosing issues.
42 |
43 | [Complete documentation for setting this up can be found in the wiki](https://github.com/Microsoft/TypeScript/wiki/Standalone-Server-%28tsserver%29#logging). Here's a summary:
44 |
45 | * Close Visual Studio
46 | * From a command prompt:
47 | * Run `setx TSS_LOG "-level verbose -file C:\tmp\tsserver.log"` (you can use a different path than `C:\tmp`, naturally)
48 | * `mkdir C:\tmp` (TS Server won't create this by default)
49 | * Start Visual Studio
50 | * Reproduce the issue
51 | * Close Visual Studio
52 | * `setx TSS_LOG ""`
53 | * Copy `C:\tmp\tsserver.log` as the next TypeScript/JavaScript language service will overwrite it
54 |
55 | Some notes and tips about `tsserver.log`:
56 | * To minimize the log file size, open as few documents as needed.
57 | * Some file contents may be visible in the log. Treat this with the same security you would the code itself.
58 | * The log gets quickly gets very large. Perform the minimum steps to reproduce the issue and immediately close Visual Studio.
59 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## The TypeScript wiki
2 |
3 | > This repo is a mirror of [the TypeScript wiki](https://github.com/Microsoft/TypeScript/wiki).
4 | > Changes on either the wiki or this repo are immediately mirrored to the other side.
5 | > This is done in a GitHub Action [here](.github/workflows/sync.yml), and [another](https://github.com/microsoft/TypeScript/blob/main/.github/workflows/sync-wiki.yml) in the TS repo, and the main work is done by a [`sync` script](.github/workflows/sync).
6 |
7 | The wiki root is [Home.md](./Home.md).
8 |
9 | You can run this locally if you have ruby installed via:
10 |
11 | ```sh
12 | # Install the deps
13 | gem install gollum
14 |
15 | # Start the server
16 | gollum
17 | ```
18 |
19 | Then you can open: `http://localhost:4567`
20 |
21 | Things to remember:
22 |
23 | - Gollum is a bit of a nightmare for testing, my current technique is:
24 |
25 | ```sh
26 | # before
27 | git branch -b thing_i_am_working_on
28 |
29 | # to iterate, amend the commit and re-run gollum against that bit of git
30 | git add .; git commit --amend --no-edit --no-verify; gollum --ref thing_i_am_working_on
31 | ```
32 |
33 | - Wikis don't support nesting, so filenames have to get a bit wild
34 |
35 | ```diff
36 | - compiler/testing/fourslash.md
37 | + compiler-testing-fourslash.md
38 | ```
39 |
40 | - You can use a custom link syntax for references to TypeScript code which will
41 | be looked up at deploy time:
42 |
43 | ```
44 | link to [`runFourSlashTest`][0]
45 |
46 | [0]:
47 | ```
48 |
49 | Will look at the file `src/harness/fourslash.ts` in microsoft/TypeScript to
50 | find the line of code `function runFourSlashTest` and provide a direct link
51 | in the wiki. You can audit them via the script `npm run lint`.
52 |
53 | # Contributing
54 |
55 | This project welcomes contributions and suggestions. Most contributions require you to agree to a
56 | Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
57 | the rights to use your contribution. For details, visit https://cla.microsoft.com.
58 |
59 | When you submit a pull request, a CLA-bot will automatically determine whether you need to provide
60 | a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions
61 | provided by the bot. You will only need to do this once across all repos using our CLA.
62 |
63 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
64 | For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
65 | contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
66 |
67 | # Legal Notices
68 |
69 | Microsoft and any contributors grant you a license to the Microsoft documentation and other content in this repository under the [Creative Commons Attribution 4.0 International Public License](https://creativecommons.org/licenses/by/4.0/legalcode), see the [LICENSE](LICENSE) file, and grant you a license to any code in the repository under the [MIT License](https://opensource.org/licenses/MIT), see the [LICENSE-CODE](LICENSE-CODE) file.
70 |
71 | Microsoft, Windows, Microsoft Azure and/or other Microsoft products and services referenced in the documentation may be either trademarks or registered trademarks of Microsoft in the United States and/or other countries.
72 | The licenses for this project do not grant you rights to use any Microsoft names, logos, or trademarks.
73 | Microsoft's general trademark guidelines can be found at http://go.microsoft.com/fwlink/?LinkID=254653.
74 |
75 | Privacy information can be found at https://privacy.microsoft.com/en-us/
76 |
77 | Microsoft and any contributors reserve all other rights, whether under their respective copyrights, patents, or trademarks, whether by implication, estoppel or otherwise.
78 |
--------------------------------------------------------------------------------
/Release-Activities.md:
--------------------------------------------------------------------------------
1 | This is the list of release activities needed for every TypeScript release.
2 | [Additional activities](#additional-activities) are also needed if a new syntax is introduced or a new compiler option gets added.
3 |
4 | The primary people managing a release should oversee these tasks along with the [overall release process](https://github.com/microsoft/TypeScript/wiki/TypeScript's-Release-Process).
5 |
6 | ## Release Candidate Activities
7 |
8 | ### tslib
9 |
10 | * [ ] Add all tslib updates
11 | * [ ] Review next version number
12 |
13 | ### `@definitelytyped/typescript-versions` and `@definitelytyped/typescript-packages`
14 |
15 | Once `main`'s version is updated, the @definitelytyped packages must be aware of the nightly's new version so that nightly versions of ATA continue to work. ATA relies on `tsX.Y` tags on `@types/*` packages.
16 |
17 | * [ ] Update [@definitelytyped/typescript-versions](https://github.com/Microsoft/DefinitelyTyped-tools/tree/main/packages/typescript-versions) and [@definitelytyped/typescript-packages](https://github.com/microsoft/DefinitelyTyped-tools/tree/main/packages/typescript-packages) to support ***the next version***, update tests, and [publish a new release](https://github.com/microsoft/DefinitelyTyped-tools/blob/main/README.md#publishingdeploying).
18 | * in other words, if we're releasing TypeScript 3.9, DefinitelyTyped needs to support `4.0`.
19 | * An [example PR](https://github.com/microsoft/DefinitelyTyped-tools/pull/1048)
20 |
21 | ## Release Activities
22 |
23 | ### Release
24 |
25 | * [ ] [Tag](https://github.com/Microsoft/TypeScript/tags) release branch
26 | * [ ] Draft and publish new [release](https://github.com/Microsoft/TypeScript/releases)
27 | * [ ] Close milestone corresponding to the release
28 |
29 | ### Project Health
30 |
31 | * [ ] Review perf dashboard to identify regressions
32 | * [ ] Review [crawler-discovered crashes](https://github.com/microsoft/TypeScript/issues?q=is%3Aissue+is%3Aopen+ServerErrors) (and ensure these have been running) (and ensure these have been running)
33 | * [ ] Review [NewErrors breaking change issues](https://github.com/microsoft/TypeScript/issues?q=is%3Aissue+is%3Aopen+NewErrors) (and ensure these have been running)
34 |
35 | ### Wiki
36 |
37 | * [ ] Update [What's new in TypeScript](https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript)
38 | * [ ] Update [Breaking Changes](https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes)
39 | * [ ] Update [API Breaking Changes](https://github.com/Microsoft/TypeScript/wiki/API-Breaking-Changes)
40 |
41 | ### Handbook
42 |
43 | * [ ] Add new [Release Notes page](https://github.com/Microsoft/TypeScript-Handbook/tree/master/pages/release%20notes) for the new release
44 | * [ ] Update [Handbook](https://github.com/Microsoft/TypeScript-Handbook) (As needed)
45 |
46 | #### npm
47 |
48 | * [ ] Publish new version of [typescript](https://www.npmjs.com/package/typescript)
49 | * [ ] Publish new version of [tslib](https://www.npmjs.com/package/tslib) (if needed) by creating a tag
50 |
51 | #### Nuget
52 |
53 | * [ ] Publish new release to https://www.nuget.org/packages/Microsoft.TypeScript.MSBuild/
54 |
55 | #### Visual Studio Marketplace
56 |
57 | * [ ] Publish VS 2015 and VS 2017 installers under [TypeScript team](https://marketplace.visualstudio.com/search?term=publisher%3A%22TypeScript%20Team%22&target=VS&category=All%20categories&vsVersion=&sortBy=Relevance)
58 |
59 | #### TypeScript-Sublime-Plugin
60 |
61 | * [ ] Update version of [tsserver](https://github.com/Microsoft/TypeScript-Sublime-Plugin/tree/master/tsserver), test, and tag
62 |
63 | #### dtslint and types-publisher
64 |
65 | After the release version is published to npm:
66 |
67 | * [ ] Update [@definitelytyped/typescript-versions](https://github.com/Microsoft/DefinitelyTyped-tools/tree/master/packages/typescript-versions): move the newly published version from `supported` to `shipped` (in the example above, that's 3.9), and publish a new release of @definitelytyped.
68 |
69 | #### Website
70 |
71 | * [ ] Update Handbook
72 | * [ ] Add new release notes page
73 |
74 | ## Additional activities
75 |
76 | When a new syntax or a new compiler option is introduced, find below the list of additional release activities needed:
77 |
78 | ### New compiler option added
79 |
80 | #### MSBuild tasks and targets
81 |
82 | * [ ] Add support for new option in MSBuild tasks and targets (see [handbook](https://github.com/Microsoft/TypeScript-Handbook/blob/master/pages/Compiler%20Options%20in%20MSBuild.md))
83 |
84 | ### New syntax introduced
85 |
86 | #### Colorization
87 |
88 | * [ ] Add colorization support in [TypeScript-TmLanguage](https://github.com/Microsoft/TypeScript-TmLanguage)
89 |
90 | #### Babel
91 |
92 | * [ ] Add parsing support in [Babylon](https://github.com/babel/babel/tree/master/packages/babylon)
93 | * [ ] Add emit support to [babel-plugin-syntax-typescript](https://github.com/babel/babel/tree/master/packages/babel-plugin-syntax-typescript)
94 | * [ ] Update the [TypeScript-Babel-Starter](https://github.com/Microsoft/TypeScript-Babel-Starter#readme) as needed
95 |
96 | #### Handbook
97 |
98 | * [ ] Add new section for the new feature in the [handbook](https://github.com/Microsoft/TypeScript-Handbook)
99 |
--------------------------------------------------------------------------------
/Resources.md:
--------------------------------------------------------------------------------
1 | ## Articles
2 |
3 | * [TypeScript at Lyft](https://eng.lyft.com/typescript-at-lyft-64f0702346ea)
4 | * [Migrating a 10,000-line legacy JavaScript codebase to TypeScript](http://www.pgbovine.net/migrating-legacy-codebase-to-typescript.htm)
5 | * [Why we love TypeScript: Delve and TypeScript](https://medium.com/@delveeng/why-we-love-typescript-bec2df88d6c2#.yonceora3)
6 | * [What is TypeScript and why would I use it in place of JavaScript? (stackoverflow.com)](http://stackoverflow.com/questions/12694530/what-is-typescript-and-why-would-i-use-it-in-place-of-javascript)
7 | * [Love for TypeScript](https://github.com/Microsoft/TypeScript/issues/10011)
8 | * [Heap Blog - Goodbye CoffeeScript, Hello TypeScript](http://blog.heapanalytics.com/goodbye-coffeescript-hello-typescript/)
9 | * [Cycligent.com/blog - TypeScript Seals My Penchant for JavaScript](https://www.cycligent.com/blog/typescript-seals-my-penchant-for-javascript/)
10 | * [Tumblr engineering on flow vs typescript](https://engineering.tumblr.com/post/165261504692/flow-and-typescript)
11 |
12 | ## Talks
13 |
14 | * [Typescript latest at ng-europe 2016](https://www.youtube.com/watch?v=o8YI2hvassE) (@DanielRosenwasser)
15 | * [//Build 2016 : What's New in TypeScript](https://www.youtube.com/watch?v=6wEVu_mkJjM) (@ahejlsberg)
16 | * [Portland TypeScript user meetup group October 2015 -- Typescript: Today and Tommrow](https://www.youtube.com/watch?v=E1s_YP-l6-A) (@DanielRosenwasser)
17 | * [Angular connect 2015 -- What is new in TypeScript](https://www.youtube.com/watch?v=_TDUV9R09PM) (@billti)
18 | * [Square tech talk 2014](https://www.youtube.com/watch?v=b69vwMIphic) (@ahejlsberg)
19 | * [//Build 2015 -- The Future of TypeScript: ECMAScript 6, Angular 2, Async/Await and Richer Libraries](https://www.youtube.com/watch?v=K6EBpMesubo) (@ahejlsberg)
20 | * [//Build 2014 -- TypeScript](https://channel9.msdn.com/Events/Build/2014/3-576) (@ahejlsberg)
21 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## Security
4 |
5 | Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/).
6 |
7 | If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://docs.microsoft.com/en-us/previous-versions/tn-archive/cc751383(v=technet.10)), please report it to us as described below.
8 |
9 | ## Reporting Security Issues
10 |
11 | **Please do not report security vulnerabilities through public GitHub issues.**
12 |
13 | Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://msrc.microsoft.com/create-report).
14 |
15 | If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://www.microsoft.com/en-us/msrc/pgp-key-msrc).
16 |
17 | You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc).
18 |
19 | Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:
20 |
21 | * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
22 | * Full paths of source file(s) related to the manifestation of the issue
23 | * The location of the affected source code (tag/branch/commit or direct URL)
24 | * Any special configuration required to reproduce the issue
25 | * Step-by-step instructions to reproduce the issue
26 | * Proof-of-concept or exploit code (if possible)
27 | * Impact of the issue, including how an attacker might exploit the issue
28 |
29 | This information will help us triage your report more quickly.
30 |
31 | If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://microsoft.com/msrc/bounty) page for more details about our active programs.
32 |
33 | ## Preferred Languages
34 |
35 | We prefer all communications to be in English.
36 |
37 | ## Policy
38 |
39 | Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://www.microsoft.com/en-us/msrc/cvd).
40 |
41 |
--------------------------------------------------------------------------------
/Setting-Compiler-Options-in-MSBuild-projects.md:
--------------------------------------------------------------------------------
1 | > ### This page has moved to http://www.typescriptlang.org/docs/handbook/compiler-options-in-msbuild.html
--------------------------------------------------------------------------------
/Spec conformance testing.md:
--------------------------------------------------------------------------------
1 | ## This page is deprecated
2 |
--------------------------------------------------------------------------------
/Standalone-Server-(tsserver).md:
--------------------------------------------------------------------------------
1 | The TypeScript standalone server (aka `tsserver`) is a node executable that encapsulates the TypeScript compiler and language services, and exposes them through a JSON protocol. `tsserver` is well suited for editors and IDE support.
2 |
3 | # Protocol
4 |
5 | ## Definition
6 |
7 | The server communication protocol is defined in the `ts.server.protocol` namespace, declared in [`tsserverlibrary.d.ts`](https://github.com/microsoft/TypeScript/blob/main/lib/tsserverlibrary.d.ts).
8 |
9 | The executable can be found in lib folder under the typescript package.
10 |
11 | ```cmd
12 | npm install --save typescript
13 | ls node_modules\typescript\lib\tsserver.js
14 | ```
15 |
16 | ## Message format
17 |
18 | `tsserver` listens on `stdin` and writes messages back to `stdout`.
19 |
20 | Requests are JSON following the protocol definition. Here is an example request to open a file `c:/DefinitelyTyped/gregorian-calendar/index.d.ts`:
21 |
22 | ```js
23 | {"seq":1,"type":"request","command":"open","arguments":{"file":"c:/DefinitelyTyped/gregorian-calendar/index.d.ts"}}
24 | ```
25 |
26 | Responses are augmented JSON format. The Message starts with a header with the content length followed by a line separator (`\r\n`) followed by the response body as a JSON string:
27 |
28 | Here is an example of a response for a `quickinfo` command:
29 |
30 | ```js
31 | Content-Length: 116
32 |
33 | {"seq":0,"type":"response","command":"quickinfo","request_seq":2,"success":false,"message":"No content available."}
34 | ```
35 |
36 | Similarly events have the same format as a response.
37 |
38 | Here is an example event for error message:
39 |
40 | ```js
41 | Content-Length: 261
42 |
43 | {"seq":0,"type":"event","event":"semanticDiag","body":{"file":"c:/DefinitelyTyped/gregorian-calendar/index.d.ts","diagnostics":[{"start":{"line":264,"offset":44},"end":{"line":264,"offset":50},"text":"Binding element 'Object' implicitly has an 'any' type."}]}}
44 | ```
45 |
46 | ## Commands
47 |
48 | `tsserver` supports a set of commands. The full list of commands supported by the server can be found under [ts.server.protocol.CommandTypes](https://github.com/microsoft/TypeScript/blob/main/src/server/protocol.ts).
49 |
50 | Each command is associated with a request and a response interface. For instance command `"completions"` corresponds to request interface `CompletionsRequest`, and response interface defined in `CompletionsResponse`.
51 |
52 | # Sample implementations
53 |
54 | ## Sublime text plugin
55 |
56 | [TypeScript-Sublime-Plugin](https://github.com/Microsoft/TypeScript-Sublime-Plugin) is a Sublime text plugin written in Python that uses `tsserver`.
57 |
58 | ## Visual Studio Code
59 |
60 | [VS Code](https://code.visualstudio.com/)'s [TypeScript support](https://github.com/microsoft/vscode/tree/master/extensions/typescript-language-features) is implemented in TypeScript using `tsserver`.
61 |
62 | ## Tide
63 |
64 | [Tide](https://github.com/ananthakumaran/tide) is an elisp implementation for emacs plugin using `tsserver`
65 |
66 | ## Neovim
67 |
68 | [nvim-typescript](https://github.com/mhartington/nvim-typescript) is a neovim plugin using `tsserver`
69 |
70 | # Advanced topics
71 |
72 | ## Logging
73 |
74 | `tsserver` logging is configured through the `TSS_LOG` environment variable.
75 |
76 | `TSS_LOG` can have the following format:
77 |
78 | ```cmd
79 | [-level ]
80 | [-traceToConsole ]
81 | [-logToFile ]
82 | [-file ]
83 | ```
84 |
85 | Note: `file` defaults to `__dirname\.log` if not specified
86 |
87 | **Example**: `set TSS_LOG=-level verbose -file c:\tmp\tsserver.log`
88 |
89 | ## Cancellation
90 |
91 | `tsserver` on startup will try to load module `./cancellationToken` from the containing directory. This module should export a factory function that accepts a list of command line arguments and returns [HostCancellationToken](https://github.com/Microsoft/TypeScript/blob/master/src/services/types.ts#L119-L121). `tsserver` will use this token to check if in-flight operation should be cancelled.
92 |
93 | NOTE: This token will be used for all operations so if one operation is cancelled and cancellation was reported through the token then when another operation is started - token should be reset into the non-cancelled state.
94 |
95 | Default implementation of the cancellation token uses the presence of named pipes as a way to signal cancellation.
96 |
97 | 1. Before spawning the server, the client generates a unique name. This name is passed to the server as a `cancellationPipeName` command line argument.
98 | 2. If some operation on the client side should be cancelled - client opens a named pipe with a name generated on step 1. Nothing needs to be written in the pipe - default cancellation token will interpret the presence of named pipe as a cancellation request.
99 | 3. After receiving acknowledgment from the server, the client closes the pipe so it can use the same pipe name for the next operation.
100 |
101 | Server can split execution of some commands (like `geterr`) in a few steps that will be executed with a delay. This allows it to react on user actions more promptly and not run heavy computations if their results will not be used. However, it introduces a tricky moment in support of cancellations. By allowing request to be suspended and resumed later we break the invariant that was the cornerstone for default implementation of cancellation. Namely now requests can overlap so one pipe name can no longer be used because client have no reason what request is currently executing and will be cancelled. To deal with this issue `tsserver` allows pipe name to be computed dynamically based on current request id. To enable this the client need to provide a value that ends with `*` as the `--cancellationPipeName` argument. If provided cancellation pipe name ends with `*` then default implementation of cancellation token will build expected pipe name as ``. This will allow client to signal any request it thinks is in flight by creating a named pipe with a proper name. Note that server will always send `requestCompleted` message to denote that asynchronous request was completed (either by running to completion or via cancellation) so the client can close named pipe once this message is received.
102 |
103 | ## Commandline options
104 |
105 | Option | Description
106 | ------------------------------|-------------
107 | `--cancellationPipeName` | Name of the pipe used as a request cancellation semaphore. See [Cancellation](#cancellation) for more information.
108 | `--syntaxOnly` | A streamlined mode for when the server will only be answering syntactic queries.
109 | `--suppressDiagnosticEvents` | Opt out of receiving events when new diagnostics are discovered (i.e. must request them explicitly).
110 | `--eventPort` | Port used for receiving events. If non is specified events are sent to stdout.
111 | `--useSingleInferredProject` | Put all open .ts and .js files that do not have a .tsconfig file in a common project
112 | `--noGetErrOnBackgroundUpdate`| Opt out of starting `getErr` on `projectsUpdatedInBackground` event
113 | `--locale` | The locale to use to show error messages, e.g. en-us.
Possible values are:
► English (US): `en`
► Czech: `cs`
► German: `de`
► Spanish: `es`
► French: `fr`
► Italian: `it`
► Japanese: `ja`
► Korean: `ko`
► Polish: `pl`
► Portuguese(Brazil): `pt-BR`
► Russian: `ru`
► Turkish: `tr`
► Simplified Chinese: `zh-CN`
► Traditional Chinese: `zh-TW`
114 |
115 | # Project System
116 |
117 | There are three kinds of projects:
118 |
119 | ## Configured Project
120 |
121 | Configured projects are defined by a configuration file, which can be either `tsconfig.json` file or a `jsconfig.json` file.
122 | That configuration file marks the project root path and defines what files to include.
123 | The configuration file also provide the compiler options to be used for this project.
124 |
125 | You can find more information in the [tsconfig.json documentation](http://www.typescriptlang.org/docs/handbook/tsconfig-json.html).
126 |
127 | ## External Project
128 |
129 | An external project represents host-specific project formats that TS is not aware of.
130 | The host is responsible for supplying the list of files in this project and compiler options to use.
131 |
132 | Currently VS is the only consumer of this type of project, to model the TS/JS files in a .csproj project.
133 |
134 |
135 | ## Inferred Project
136 |
137 | Inferred projects are what is used to represent a loose TS/JS file.
138 | If a file does not have a configuration file (`tsconfig.json` or `jsconfig.json`) **in the current directory or any parent directories**, the server will create an inferred project for it.
139 |
140 | The server will include the loose file, then includes all other files included by triple slash references and module imports from the original file transitively.
141 |
142 | Compilation options will use the default options for inferred projects.
143 | The host can set the defaults of an inferred project.
144 |
145 | ## Relationship Among These Projects
146 |
147 | In general, the relationship can be summarized as `configured projects > external projects > inferred projects`.
148 |
149 | For example, if `file1.ts` belongs to an inferred project, but later a new `tsconfig.json` also includes this file.
150 | Then after the `tsconfig.json` file is found, `file1.ts` will no longer belong to the previous inferred project but the newly created configured project instead.
151 | If `file1.ts` used to be the root file of the inferred project, that inferred project will now be destroyed; otherwise it will remain with one fewer file.
152 |
153 | For another example, if a `tsconfig.json` file is created to include some files used to belong to an external project (let's call it EP1), then in the current implementation EP1 will be destroyed, all its files either go to the new configured project or will belong to a new inferred project the next time it is opened.
154 |
155 | One thing to notice is that one file can belong to multiple projects of the same kind at the same time. E.g., a file can be included by multiple configured projects / inferred projects / external projects.
156 |
157 |
158 |
--------------------------------------------------------------------------------
/Tooling-On-The-Compiler-Repo.md:
--------------------------------------------------------------------------------
1 | ## Tooling which runs microsoft/TypeScript
2 |
3 | The TypeScript compiler repo has a few different automation tools running on it.
4 | This document is a rough map of what is running and where you can find the code.
5 |
6 | ### @typescript-bot
7 |
8 | The bot which handles commands in GitHub comments like:
9 |
10 | ```
11 | @typescript-bot pack this
12 | ```
13 |
14 | Is fully documented on [the wiki here](https://github.com/microsoft/TypeScript/wiki/Triggering-TypeScript-Bot) and the source code live at [`weswigham/typescript-bot-test-triggerer`](https://github.com/weswigham/typescript-bot-test-triggerer) .
15 |
16 | ### Label Bots
17 |
18 | The bot which adds/removes labels and assignees lives at [microsoft/TypeScript-repos-automation](https://github.com/microsoft/TypeScript-repos-automation) and on [Azure here](https://ms.portal.azure.com/#@microsoft.onmicrosoft.com/resource/subscriptions/57bfeeed-c34a-4ffd-a06b-ccff27ac91b8/resourceGroups/typescriptreposautomatio/providers/Microsoft.Web/sites/TypeScriptReposAutomation).
19 |
20 | ### Repros
21 |
22 | A scheduled task which evaluates code samples generated in [the Bug Workbench](https://www.typescriptlang.org/dev/bug-workbench).
23 |
24 | This automation runs via a [daily GitHub Action](https://github.com/microsoft/TypeScript/blob/master/.github/workflows/twoslash-repros.yaml) where the majority of the code lives at [`microsoft/TypeScript-Twoslash-Repro-Action`](https://github.com/microsoft/TypeScript-Twoslash-Repro-Action)
25 |
26 | ### Other webhooks
27 |
28 | We've got a few out-going webhooks:
29 |
30 | - We send PRs Issues and Pushes to [Gitter](https://gitter.im/Microsoft/TypeScript)
31 | - We send PRs Issues and Pushes to [Discord](https://discord.gg/TypeScript)
32 |
33 | Which is mainly just to provide a high level insight for community members.
34 |
35 | Projects which I could not find a source or Azure link for:
36 |
37 | - fabricbot-typescript
38 | - trialgithubcommentresponder
39 |
--------------------------------------------------------------------------------
/Triage-Instructions.md:
--------------------------------------------------------------------------------
1 | # Label Bugs
2 |
3 | The highest priority is getting unlabeled bugs to zero.
4 |
5 | [Query: Open Unlabeled Issues](https://github.com/Microsoft/TypeScript/issues?utf8=%E2%9C%93&q=is%3Aopen%20is%3Aissue%20no%3Alabel%20sort%3Acreated-desc)
6 |
7 | # How to Label a Bug
8 |
9 | ### Change the Title
10 |
11 | Most issues have pretty bad titles, hindering future searches. If needed, edit the issue title to align better with the [[Preferred Issue Titles]] format.
12 |
13 | If you can't figure out from the issue report what the title *should* be, then you'll definitely need clarification from the user (see "Needs More Info" below).
14 |
15 | ### Add a Label
16 |
17 | Classify the bug accordingly:
18 | * Duplicate: Many issues are duplicates, so try to find an original
19 | * If you do, add the `Duplicate` label and add a comment e.g. "See #1234567"
20 | * If it's clearly an exact duplicate, Close
21 | * Optional: If the user would have found this with a trivial search (e.g. searching for the title of their own bug), gently remind them to search before logging new issues
22 | * Legitimate bug (crash, incorrect behavior, etc.): Add the `Bug` label
23 | * Optionally add `High Priority` if it's an easy-to-hit crash or incorrect emit
24 | * Optionally add one of the `Domain:` labels if you'd like to
25 | * Suggestion
26 | * Add `Suggestion` and `In Discussion` if this is something that can be looked at immediately
27 | * Add `Suggestion`, `Out of Scope`, and close if the suggestion is not something we would ever do (change JS runtime semantics, emit Python, switch to Haskell's type system, etc). Add a comment pointing to the [Design Goals](https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals) Wiki page
28 | * Add `Suggestion`, `Needs Proposal` if something requiring a more formal description is required. Add a comment indicating what's needed
29 | * Question (the user is explicitly asking for help)
30 | * Add the `Question` label
31 | * Provide an answer if it's easy for you to do so, otherwise point them at [Stack Overflow](https://stackoverflow.com/questions/tagged/typescript) and remind that the issue tracker is not a support forum
32 | * Close the bug if it's egregiously out of scope (e.g. asking for help getting Angular2 working or whatever)
33 | * If the question is about the compiler API and you can't answer it immediately, assign to a dev
34 | * Not a bug
35 | * Add `Working as Intended` if the behavior is truly done on purpose, or `Design Limitation` if it's something we *would* fix in a perfect world but are unable to do so
36 | * Post a comment explaining why. Try to reference things from [the FAQ](https://github.com/Microsoft/TypeScript/wiki/FAQ) if applicable; consider updating the FAQ if you think it's a common question
37 | * It's not clear what the issue is describing
38 | * Add the `Needs More Info` label
39 | * Add a comment explaining why the issue isn't actionable yet
40 | * Issue is in external component (e.g. tslint, awesome-typescript-loader, etc)
41 | * Add the `External` label
42 | * Explain why
43 | * Completely useless
44 | * If the issue is completely unsalvageable (e.g. it's just "Why can TypeScript not for C# now?" with no other info), add the `Unactionable` label and Close.
45 | * Fallback: Not sure
46 | * Add "Needs Investigation" label
47 | * Optional: Post comment with your thoughts (e.g. "Might be a type inference bug, need to investigate")
48 |
49 | # Investigate
50 |
51 | Once there are no new unlabeled bugs, start looking at issues which need investigation:
52 | [Query: Bugs needing investigation](https://github.com/Microsoft/TypeScript/issues?q=is%3Aopen+is%3Aissue+label%3A%22Needs+Investigation%22)
--------------------------------------------------------------------------------
/Triggering-TypeScript-Bot.md:
--------------------------------------------------------------------------------
1 | If you're a TS maintainer, you can respond to a PR with a comment similar to
2 | ```
3 | @typescript-bot [test command]
4 | ```
5 | to trigger a specialized on-demand build on the PR.
6 |
7 | The following command triggers a set of the more common on-demand tests:
8 | ```
9 | @tyepscript-bot test it
10 | ```
11 |
12 | This will trigger the `test top400`, `user test this`, `run dt`, `perf test this faster` commands.
13 |
14 | The currently recognized commands are:
15 | * [`run dt`](https://typescript.visualstudio.com/TypeScript/_build?definitionId=23) - The runs the definitely typed linter using the PR TS build sharded across 4 worker containers (this takes around 25 minutes).
16 | * [`run dt slower`](https://typescript.visualstudio.com/TypeScript/_build?definitionId=18) - This is the same as the above, but only on a single worker (this takes around 90 minutes). This is useful if the results aren't needed promptly and the build queue is busy.
17 | * [`user test this`](https://typescript.visualstudio.com/TypeScript/_build?definitionId=47) - This runs the nightly-tested `user` suite against the PR and against main (this takes around 30 minutes). The bot will post a summary comment comparing results from the two.
18 | * [`user test tsserver`](https://typescript.visualstudio.com/TypeScript/_build?definitionId=47) - This runs the nightly-tested `user` suite against the PR and against main (this takes around 30 minutes). The bot will post a summary comment comparing results from the two. This variant also tests tsserver, not just tsc.
19 | * [`user test this slower`](https://typescript.visualstudio.com/TypeScript/_build?definitionId=24) - The older version of the user tests, and run on only a single container, meaning it takes around 1h 30m. The nightly run is run using this build.
20 | * [`test top100`](https://typescript.visualstudio.com/TypeScript/_build?definitionId=47) - This runs the top 100 TypeScript repos on GitHub, by stars, against the PR and against main (this takes around 30 minutes). The bot will post a summary comment comparing results from the two.
21 |
22 | Note that `100` can be replaced with any other number up to 3 digits. For example, `test top200`, `test top50`, or `test top999` will all work.
23 | * [`test tsserver top100`](https://typescript.visualstudio.com/TypeScript/_build?definitionId=47) - This runs the top 100 TypeScript repos on GitHub, by stars, against the PR and against main (this takes around 30 minutes). The bot will post a summary comment comparing results from the two. This variant tests tsserver, not tsc.
24 |
25 | Note that `100` can be replaced with any other number up to 3 digits. For example, `test top200`, `test top50`, or `test top999` will all work.
26 | * [`perf test`](https://typescript.visualstudio.com/TypeScript/_build?definitionId=69) - This queues a build on our perf server using the code from the PR - once started (which will only happen once any currently running build is done), this takes around 25 minutes. The bot should post the results of the perf test run back into the triggering PR once done.
27 | * [`perf test faster`](https://typescript.visualstudio.com/TypeScript/_build?definitionId=69) - This is the same as the above, but only runs tsc tests.
28 | * [`pack this`](https://typescript.visualstudio.com/TypeScript/_build?definitionId=19) - This creates a build which does a build, runs an LKG, runs normal tests, and then packs the result into an installable tarball (which can be downloaded from the build artifacts on the azure pipelines build status page), perfect for installing with `npm i ` to test with.
29 | * [`cherry-pick this to branchname`](https://typescript.visualstudio.com/TypeScript/_build?definitionId=30) - This launches a task to squash the commits from the PR and then open a new PR that cherry-picks the change into branch `branchname`. This takes about 5 minutes as the build agent needs to clone the input PR. The bot should reply if something goes wrong, or otherwise once the new PR is open.
30 | * [`cherry-pick this to branchname and LKG`](https://typescript.visualstudio.com/TypeScript/_build?definitionId=30) - Same as above, but an LKG commit will be added onto the PR after the squashed cherry-pick commit.
31 | * `run repros` - Triggers inline code repro workflow
32 |
33 | In addition, there are a small suite of commands which work in _any_ comment and relate to release management.
34 | You can see how these are typically used in our documented [comment command sequence](https://github.com/microsoft/TypeScript/wiki/TypeScript's-Release-Process#the-comment-command-sequence):
35 |
36 | * [`create release-X.Y`](https://github.com/microsoft/TypeScript/actions/workflows/new-release-branch.yaml) This makes a `release-X.Y` branch (replace `X.Y` with your desired version) with the `package.json` version set to `X.Y.0-beta`, the `corePublic` `versionMajorMinor` set to `X.Y`, and the full `ts.version` string set to `X.Y.0-beta`, and updates the accompanying baselines. An LKG is then performed. This new branch is directly pushed to `microsoft/TypeScript`. In short, this fully sets up a new release branch to be ready to publish a beta.
37 | * [`bump release-X.Y`](https://github.com/microsoft/TypeScript/actions/workflows/set-version.yaml) This bumps the version (`0-beta` -> `1-rc` -> `2` -> `3` and so on) on the specified branch and captures a new LKG, essentially preparing the branch for a new release.
38 | * [`sync release-X.Y`](https://github.com/microsoft/TypeScript/actions/workflows/sync-branch.yaml) This merges `master` into the specified branch; this is useful for syncing the branch with `master` in the period between the beta and rc.
39 |
40 | A single comment may contain multiple commands, so long as each is prefixed with a call to `@typescript-bot`.
41 |
42 | The source of the webhook running the bot is currently available [here](https://github.com/microsoft/typescript-bot-test-triggerer).
43 |
44 | Here is the usual invocation of all the useful bot commands at once:
45 |
46 | ```ts
47 | @typescript-bot test top100
48 | @typescript-bot test tsserver top100
49 | @typescript-bot user test this
50 | @typescript-bot user test tsserver
51 | @typescript-bot run dt
52 | @typescript-bot perf test this
53 | @typescript-bot pack this
54 | ```
55 |
56 | You can [put this into a saved reply](https://github.com/settings/replies) so it's easily accessible.
57 |
--------------------------------------------------------------------------------
/Type-Checking-JavaScript-Files.md:
--------------------------------------------------------------------------------
1 | > ### This page has moved to https://www.typescriptlang.org/docs/handbook/type-checking-javascript-files.html
--------------------------------------------------------------------------------
/TypeScript's-Release-Process.md:
--------------------------------------------------------------------------------
1 | # How Do I Track Releases?
2 |
3 | ## Tracking Planning and Development
4 |
5 | Each release has a corresponding [Iteration Plan](https://github.com/microsoft/TypeScript/issues?q=is%3Aissue+label%3APlanning+%22Iteration+Plan) issue on GitHub.
6 | These iteration plans contain a list of **planned work items** as well as **planned release dates**.
7 |
8 | We also keep an updated [Feature Roadmap](https://github.com/Microsoft/TypeScript/wiki/Roadmap) which is typically more accurate in terms of what we release.
9 |
10 | ## Tracking Actual Releases
11 |
12 | The TypeScript team also maintains the official [TypeScript Blog](https://devblogs.microsoft.com/typescript/) where releases are announced.
13 |
14 | The official TypeScript social media accounts also post release announcements:
15 |
16 | * [bsky.app/profile/typescriptlang.org](https://bsky.app/profile/typescriptlang.org)
17 | * [fosstodon.org/@TypeScript](https://fosstodon.org/@TypeScript)
18 | * [twitter.com/typescript](https://twitter.com/TypeScript)
19 |
20 | # What Are the Stages of a Release?
21 |
22 | TypeScript currently has two pre-releases (the Beta and the Release Candidate), followed by a stable "final" release, followed by any number of patches.
23 |
24 | ```
25 | TS 4.1.0 (Beta) ----> TS 4.1.1 (RC) ------> TS 4.1.2 (Stable) ------> TS 4.1.3 (patch) ---> ...
26 | / /
27 | / / TS 4.2.0 (Beta) ---> TS 4.2.1 (RC) ---> ...
28 | / / /
29 | main ---------------------------------------------------------------> ...
30 | ```
31 |
32 | # How Often Does TypeScript Release?
33 |
34 | In general you can expect a release **around every 3 months**.
35 | TypeScript's release cadence is relatively regular in this respect, though there may occasionally be some variance due to holidays and other scheduling concerns.
36 |
37 | The breakdown across pre-release versions is typically
38 |
39 | * Betas are released about 4 weeks after the prior Stable release.
40 | * Release Candidates are released around 6 weeks after the prior Beta.
41 | * Stable releases are released around 2 weeks after the prior Release Candidate.
42 | * Patches are released at any frequency depending on urgency, but we evaluate at the end of every month whether a patch should be published for the current stable release.
43 |
44 | # What Work Gets Done?
45 |
46 | ## What gets done for the Beta?
47 |
48 | During the beta, new features, breaking changes, and bug fixes are prioritized.
49 | Breaking changes and features are "front-loaded" so that they can get ample testing in the beta and RC.
50 | It also ensures we can roll back changes before there is too much momentum in a release.
51 | We strive to get these in as early as possible so that they are available in [nightly releases](https://www.typescriptlang.org/docs/handbook/nightly-builds.html).
52 |
53 | ***We strive not to make breaking changes after the Beta release.***
54 |
55 | ## What gets done for the Release Candidate?
56 |
57 | Following the beta release, work is done that leads to a Release Candidate (RC).
58 | The RC primarily contains bug fixes and often editor features that were not finished in time for the Beta.
59 | Editor features are okay to go in here because they are relatively easy to back out in time (given dog-fooding, user expectations, the possibility of flagging, lag in editor rollout, and patch releases).
60 |
61 | Once the RC goes out, the team begins focus on the next version of TypeScript.
62 |
63 | ***Very few changes should be expected for a version after the Release Candidate.***
64 |
65 | ## What gets done for the Stable/Final release?
66 |
67 | High-priority fixes are applied following the Release Candidate for the Stable release.
68 |
69 | By default, new bugs that are not regressions from the upcoming or prior version of TypeScript will be addressed in a new minor version following the final release.
70 |
71 | ## What gets done for patch releases?
72 |
73 | Patch releases are periodically pushed out for any of the following:
74 |
75 | * High-priority regression fixes
76 | * Performance regression fixes
77 | * Safe fixes to the language service/editing experience
78 |
79 | These fixes are typically weighed against the cost (how hard it would be for the team to retroactively apply/release a change), the risk (how much code is changed, how understandable is the fix), as well as how feasible it would be to wait for the next version.
80 |
81 | # Which Version Should I Be Using?
82 |
83 | We always appreciate early feedback on new versions of the language and editor support!
84 | Depending on how you'd like to test TypeScript and contribute, there are a couple of different options.
85 |
86 | ## Testing Independently
87 |
88 | Despite what the name might imply, [nightly versions](https://www.typescriptlang.org/docs/handbook/nightly-builds.html) are always the preferred way to test out the current state of TypeScript.
89 | While we won't necessarily endorse them for production use, nightlies are always fairly stable and easy to use.
90 |
91 | You can download a nightly release via npm (`npm install typescript@next`) and configure your editor support.
92 | If you can't commit to updating your build processes yet, but you write code in Visual Studio Code, you can use the [TypeScript and JavaScript Nightly](https://marketplace.visualstudio.com/items?itemName=ms-vscode.vscode-typescript-next) extension to at least try out new versions of our editor support.
93 |
94 | ## Testing New Features
95 |
96 | If you're willing to try new features, we make Beta releases available.
97 | This is often a good period to start providing feedback on new features, and the closer to the beta release that feedback occurs, the easier we can address it before it officially is added to the language.
98 |
99 | The longer you wait after a beta, the less actionable your feedback will be.
100 | In those cases, we encourage you to switch to the nightly releases.
101 |
102 | ## Testing for High-Priority Bug Fixes
103 |
104 | If you are extremely limited in your ability to provide feedback, the Release Candidate is the most stable pre-release we provide.
105 | Feedback on the Release Candidate can be addressed, but it is typically limited to high-priority bug fixes, not fundamental changes.
106 |
107 | If you intend to provide feedback that will fundamentally affect the design of the language, it should ideally be provided before the RC.
108 | If that is the case, do not wait until the release candidate.
109 | Use nightly releases to test on your own or within your team/organization!
110 |
111 | ## Staying Up-to-Date
112 |
113 | If you can't commit any feedback, just stay up to date on the latest version of TypeScript.
114 | Dedicate a day or two every 3 months or so to perform the upgrade.
115 |
116 | _____________
117 | _____________
118 |
119 | The following section is targeted more at maintainers and contributors!
120 | If you're simply consuming TypeScript, it is probably not relevant.
121 |
122 | # Release Mechanics
123 |
124 | The TypeScript team develops around one central branch: `main`.
125 | This branch is used for [nightly builds](https://www.typescriptlang.org/docs/handbook/nightly-builds.html), and is the source of truth.
126 | This central branch is always meant to build cleanly.
127 |
128 | # The Typical Release Schedule
129 |
130 | The typical release schedule for a version `X.Y` looks like
131 |
132 | 1. Create X.Y Beta (X.Y.0) Build for Testing
133 | 1. **TypeScript X.Y Beta Release**
134 | 1. Create X.Y RC (X.Y.1) Build for Testing
135 | 1. **TypeScript X.Y RC Release**
136 | 1. Create X.Y Final (X.Y.2) Build for Testing
137 | 1. **TypeScript X.Y Final Release**
138 | 1. Then every week evaluate whether the following needs to be done:
139 | 1. Cherry-pick prioritized new work into the X.Y branch
140 | 1. Release a new patch version
141 |
142 | # How Branching Works Around Releases
143 |
144 | What does the team have to do to achieve that typical release schedule?
145 |
146 | 1. Development always just occurs on the `main` branch. This is the default assumption.
147 | 1. When we need to create the beta build for TypeScript X.Y, we create a branch called `release-X.Y` and bump the version to `X.Y.0-beta`. On npm, this is published with `--tag beta`.
148 | 1. Development for TypeScript X.Y **continues on the `main` branch**.
149 | 1. When we need to create an RC build for TypeScript X.Y, we merge the `main` branch into `release-X.Y` and bump the version to `X.Y.1-rc`. On npm, this is published with `--tag rc`.
150 | 1. After the RC goes out, the assumption is that all work in `main` will go into TypeScript X.(Y + 1). **Any critical changes will need to be cherry-picked to `release-X.Y`**.
151 | 1. When we need to create a build for the stable release version of TypeScript X.Y, we bump the version to `X.Y.2` (with no pre-release version string or tag). On npm, this is published with `--tag latest`.
152 |
153 | ## The Comment Command Sequence
154 |
155 | Much of this process is automated by [Triggering @typescript-bot](https://github.com/microsoft/TypeScript/wiki/Triggering-TypeScript-Bot) to perform tasks, along with a few GitHub actions.
156 | Typically, commands to the bot are given [in the Iteration Plan comments of a release](https://github.com/microsoft/TypeScript/issues?q=is%3Aissue+label%3APlanning+%22Iteration+Plan%22+).
157 | The commands roughly occur in the following order:
158 |
159 | 1. Readying a Beta
160 | 1. Comment `@typescript-bot create release-X.Y` (create the branch)
161 | 1. In the event that changes need to come in after:
162 | 1. Comment `@typescript-bot sync release-X.Y`
163 | 1. Run [Update LKG](https://github.com/microsoft/TypeScript/actions/workflows/update-lkg.yml) on `release-X.Y`.
164 | 1. Readying an RC
165 | 1. Comment `@typescript-bot sync release-X.Y` (sync `main` to `release-X.Y`)
166 | 1. Comment `@typescript-bot bump release-X.Y` (update the version number and LKG)
167 | 1. In the event that changes need to come in after:
168 | 1. Comment `@typescript-bot sync release-X.Y`
169 | 1. Run [Update LKG](https://github.com/microsoft/TypeScript/actions/workflows/update-lkg.yml) on `release-X.Y`.
170 | 1. Readying a Stable (or patch) Release
171 | 1. On PRs that you want to cherry-pick, run `@typescript-bot cherry-pick this to release-X.Y`.
172 | 1. Comment `@typescript-bot bump release-X.Y` (update the version number)
173 | 1. If another PR comes in afterwards, you can run a combined cherry-pick/LKG with the comment `@typescript-bot cherry-pick this to release-X.Y and LKG`
174 | 1. Run [Update LKG](https://github.com/microsoft/TypeScript/actions/workflows/update-lkg.yml) on `release-X.Y` if necessary.
175 |
176 | # Release Tasks
177 |
178 | Every publish, especially the Beta, RC, and Stable releases, must undergo a set of release activities.
179 | These release activities are documented [here](https://github.com/microsoft/TypeScript/wiki/Release-Activities).
180 |
181 | # Publishing
182 |
183 | The publishing process is largely internal at the moment, but it is also largely uninteresting.
184 |
185 | The most interesting portion of this is the fact that a Visual Studio build is created, typically 2-3 business days prior to a release, so that a testing team can perform a validation pass.
186 | This validation pass sometimes finds regressions in both the core TypeScript experience as well as the TypeScript/JavaScript editing experience.
187 |
188 | # FAQ
189 |
190 | ## Why do you need to set the patch version on pre-releases?
191 |
192 | I think some weirdness around publishing extensions to the Visual Studio marketplace.
193 | To accomodate it and stay reasonable, we just version consistently across npm, NuGet, and VS Marketplace.
--------------------------------------------------------------------------------
/TypeScript-Deployment.md:
--------------------------------------------------------------------------------
1 | ### LKG
2 |
3 | The version of TypeScript which is published to npm comes from the Last Known Good (LKG) version of TypeScript. The bundled version of the LKG build is committed into the repo inside the [lib](https://github.com/microsoft/TypeScript/tree/master/lib) as is always available.
4 |
5 | The LKG version of TypeScript is the version of the compiler you would use to work on TypeScript inside this repo.
6 |
7 | ### Publish to NPM
8 |
9 | Publishing to npm will submit the LKG version of TypeScript to npm. This means that to update a deploy you would need to run:
10 |
11 | ```sh
12 | gulp LKG
13 | npm publish
14 | ```
15 |
16 | ### Official Releases
17 |
18 | For all our release-x branches, the node 12 build always produces a tarball based on the branch. Any one of those tarballs can be promoted (from the build UI) and published as a full release, which then triggers `npm publish`es and GitHub releases.
19 |
20 | Our workflow is to prep the release branch, bump it's version, do an LKG, then fire off that generated tarball as the release using Azure Pipelines, you can see [them here](https://dev.azure.com/typescript/TypeScript/_release?_a=releases&view=mine&definitionId=1)
21 |
22 |
--------------------------------------------------------------------------------
/TypeScript-Design-Goals.md:
--------------------------------------------------------------------------------
1 | # Introduction
2 | This document serves to outline the general design principles we have based the TypeScript language on. While it is by no means exhaustive, it aims to summarize the rules by which we've made many of the decisions that have shaped the language. Some of these rules are subjective, and at times are at odds with each other; reaching the right balance and making the right exceptions is the essence of how successful programming languages are designed.
3 |
4 | # Goals
5 | 1. Statically identify constructs that are likely to be errors.
6 | 1. Provide a structuring mechanism for larger pieces of code.
7 | 1. Impose no runtime overhead on emitted programs.
8 | 1. Emit clean, idiomatic, recognizable JavaScript code.
9 | 1. Produce a language that is composable and easy to reason about.
10 | 1. Align with current and future ECMAScript proposals.
11 | 1. Preserve runtime behavior of all JavaScript code.
12 | 1. Avoid adding expression-level syntax.
13 | 1. Use a consistent, fully erasable, structural type system.
14 | 1. Be a cross-platform development tool.
15 | 1. Do not cause substantial breaking changes from TypeScript 1.0.
16 |
17 | # Non-goals
18 | 1. Exactly mimic the design of existing languages. Instead, use the behavior of JavaScript and the intentions of program authors as a guide for what makes the most sense in the language.
19 | 1. Aggressively optimize the runtime performance of programs. Instead, emit idiomatic JavaScript code that plays well with the performance characteristics of runtime platforms.
20 | 1. Apply a sound or "provably correct" type system. Instead, strike a balance between correctness and productivity.
21 | 1. Provide an end-to-end build pipeline. Instead, make the system extensible so that external tools can use the compiler for more complex build workflows.
22 | 1. Add or rely on run-time type information in programs, or emit different code based on the results of the type system. Instead, encourage programming patterns that do not require run-time metadata.
23 | 1. Provide additional runtime functionality or libraries. Instead, use TypeScript to describe existing libraries.
24 | 1. Introduce behaviour that is likely to surprise users. Instead have due consideration for patterns adopted by other commonly-used languages.
--------------------------------------------------------------------------------
/TypeScript-Editor-Support.md:
--------------------------------------------------------------------------------
1 | # Quick List
2 |
3 | * [alm.tools](#alm)
4 | * [Atom](#atom)
5 | * [CATS](#cats)
6 | * [Eclipse](#eclipse)
7 | * [Emacs](#emacs)
8 | * [NeoVim](#neovim)
9 | * [NetBeans](#netbeans)
10 | * [Notepad++](#notepad)
11 | * [Sublime Text](#sublime-text)
12 | * [Vim](#vim)
13 | * [Visual Studio](#visual-studio-20132015)
14 | * [Visual Studio Code](#visual-studio-code)
15 | * [WebStorm](#webstorm)
16 |
17 | # alm
18 |
19 | [alm.tools](http://alm.tools/) a complete TypeScript development environment available as a simple npm package.
20 |
21 | ```shell
22 | npm i alm -g
23 | ```
24 |
25 | # Atom
26 |
27 | [Atom-TypeScript](https://atom.io/packages/atom-typescript), a TypeScript language service for Atom developed by TypeStrong
28 |
29 | # CATS
30 |
31 | [Code Assistant for TypeScript (CATS)](https://github.com/jbaron/cats) - is an open source TypeScript development environment that runs on OS X, Windows, and Linux.
32 | Since it is also written in TypeScript, it can be easily extended if required.
33 |
34 | # Eclipse
35 |
36 | * [TypeScript IDE for Eclipse](https://github.com/angelozerr/typescript.java/wiki/Getting-Started), an Eclipse plugin developed by Angelo Zerr.
37 | * [Eclipse TypeScript Plug-in](https://github.com/palantir/eclipse-typescript), an Eclipse plugin developed by Palantir.
38 |
39 | # Emacs
40 |
41 | [tide](https://github.com/ananthakumaran/tide) - TypeScript Interactive Development Environment for Emacs
42 |
43 | # NeoVim
44 |
45 | TypeScript support is enabled via the built-in [Language Server Protocol](https://neovim.io/doc/user/lsp.html) client included in NeoVim since version 0.5.
46 |
47 | # NetBeans
48 |
49 | * [nbts](https://github.com/Everlaw/nbts) - NetBeans TypeScript editor plugin
50 |
51 | # Notepad++
52 |
53 | * [notepadplus-typescript](https://github.com/chai2010/notepadplus-typescript) - Notepad++ colorization support for TypeScript.
54 |
55 | # Sublime Text
56 |
57 | The [TypeScript Plugin for Sublime](https://github.com/Microsoft/TypeScript-Sublime-Plugin), available through [Package Control](https://packagecontrol.io/) for both Sublime Text 3 and Sublime Text 2.
58 |
59 | # Vim
60 |
61 | ### Syntax highlighting
62 |
63 | * [leafgarland/typescript-vim](https://github.com/leafgarland/typescript-vim) provides syntax files for highlighting `.ts` and `.d.ts` files.
64 | * [HerringtonDarkholme/yats.vim](https://github.com/HerringtonDarkholme/yats.vim) provides more syntax highlighting and DOM keywords.
65 |
66 | ### Language Service Tools
67 |
68 | * [Quramy/tsuquyomi](https://github.com/Quramy/tsuquyomi)
69 |
70 | If you would like to have as-you-type completion, you can install [YouCompleteMe](https://github.com/Valloric/YouCompleteMe) and add the following code into your `.vimrc` to specify what token will trigger the completion. YouCompleteMe will call into its respective TypeScript Plugin for semantic queries.
71 |
72 | ```vimscript
73 | if !exists("g:ycm_semantic_triggers")
74 | let g:ycm_semantic_triggers = {}
75 | endif
76 | let g:ycm_semantic_triggers['typescript'] = ['.']
77 | ```
78 |
79 | * [mhartington/nvim-typescript](https://github.com/mhartington/nvim-typescript)
80 |
81 | As-you-type deoplete asynchronous completion framework for Vim 8. Needs [Shougo/deoplete.nvim](https://github.com/Shougo/deoplete.nvim) in order to work.
82 |
83 | * [ALE](https://github.com/w0rp/ale)
84 |
85 | ALE (Asynchronous Lint Engine) supports as-you-type completion for TypeScript out of the box.
86 |
87 | ```vimscript
88 | " Enable completion where available.
89 | " This setting must be set before ALE is loaded.
90 | let g:ale_completion_enabled = 1
91 | ```
92 |
93 | * [coc.nvim](https://github.com/neoclide/coc.nvim)
94 |
95 | Install [coc-tsserver](https://github.com/neoclide/coc-tsserver) by command:
96 |
97 | ``` vim
98 | :CocInstall coc-tsserver
99 | ```
100 |
101 | [coc-tsserver](https://github.com/neoclide/coc-tsserver) provide almost same features as typescript language extension of VSCode, including completion of function calls as snippets, auto import after completion etc.
102 |
103 | # Visual Studio
104 |
105 | [Visual Studio](https://www.visualstudio.com/) comes with TypeScript when installing Microsoft Web Tools.
106 |
107 | TypeScript for Visual Studio 2019 and Visual Studio 2017 (with [version 15.2 or later](https://www.visualstudio.com/en-us/news/releasenotes/vs2017-relnotes-v15.2)) can be found [here](https://marketplace.visualstudio.com/publishers/TypeScriptTeam)
108 |
109 | TypeScript for Visual Studio 2015 with [update 3](https://www.visualstudio.com/en-us/news/releasenotes/vs2015-update3-vs) can be found [here](http://www.microsoft.com/en-us/download/details.aspx?id=48593)
110 |
111 | TypeScript for Visual Studio 2013 can be found [here](https://www.microsoft.com/en-us/download/details.aspx?id=48739); however, its latest supported version is TypeScript 1.8.5.
112 |
113 | # Visual Studio Code
114 |
115 | [Visual Studio Code](https://code.visualstudio.com/), a lightweight cross-platform editor, comes with TypeScript support built in.
116 |
117 | # Webstorm
118 |
119 | [WebStorm](https://www.jetbrains.com/webstorm/), as well as other JetBrains IDEs, contain TypeScript language support out of the box.
120 |
--------------------------------------------------------------------------------
/TypeScript-MSBuild-In-Depth.md:
--------------------------------------------------------------------------------
1 | # Delivery Mechanism
2 |
3 | ## NuGet
4 |
5 | In releases 2.3 and above, TypeScript MSBuild can be used with MSBuild on non-Windows platforms.
6 |
7 | ### Package structure
8 |
9 | TypeScript NuGet contains two main folders
10 |
11 | * build folder
12 |
13 | Two files are located in this folder.
14 | Both are entry points - for the main TypeScript target file and props file respectively.
15 |
16 | 1. Microsoft.TypeScript.MSBuild.targets
17 |
18 | The file set variables specific to a run-time platform, such as a path to `TypeScript.Tasks.dll`, before importing `Microsoft.TypeScript.targets` from `tools` folder.
19 |
20 | 2. Microsoft.TypeScript.MSBuild.props
21 |
22 | The file imports `Microsoft.TypeScript.Default.props` from the `tools` folder and sets properties indicating that the build has been initiated through NuGet.
23 |
24 | * tools folder
25 |
26 | Earlier versions only contain a tsc folder. `Microsoft.TypeScript.targets` and `TypeScript.Tasks.dll` are located at the root level.
27 |
28 | The below structure is for versions 2.3 and above.
29 | 1. net45
30 |
31 | contains `Microsoft.TypeScript.targets`, `TypeScript.Tasks.dll` and facade dependency dlls.
32 | When building any project on a Windows platform, MSBuild uses the DLLs from this folder.
33 |
34 | 2. netstandard
35 |
36 | contains `Microsoft.TypeScript.targets` and `TypeScript.Tasks.dll`.
37 | The contents in this folder are used when building projects on a non-Window machine.
38 |
39 | 3. tsc
40 |
41 | contains `tsc.exe` and all dependency files required to execute the exe.
42 | On Windows, `TypeScript.Tasks.dll` uses the `tsc.exe` to build projects.
43 | On non-Windows, `TypeScript.Tasks.dll` uses NodeJS to run `tsc.js` - implying that it is required for NodeJS to be installed on these platforms.
44 |
45 | ## MSI Installer
46 |
47 | TypeScript is also shipped as a stand-alone exe that can be installed on a Windows machine.
48 | Currently the installer is only available for Visual Studio 2015 with Update 3.
49 |
50 | The installer install files into following folders:
51 |
52 | 1. Microsoft SDKs Folder
53 |
54 | The installer installs a sub-folder called `TypeScript` into `"%ProgramFiles%\Microsoft SDKs"`.
55 |
56 | * Before version 2.3
57 |
58 | A version-number folder is installed inside the TypeScript sub-folder in which the version-number folder contains all necessary files to execute `tsc.exe`.
59 |
60 | * Version 2.3 and above
61 |
62 | In additional to similar contents with prior version, the newer installer installs another sub-folder inside the version-number folder called *build*.
63 | This *build* folder contains `Microsoft.TypeScript.targets`, `TypeScript.Tasks.dll` and its dependencies.
64 | This allows us to be able to support side-by-side while being able to make any necessary changes to the task and target file.
65 | We also add another sub-folder called *versions* which is used by the stub target file (see: Stub Target File section) to figure out the version to use.
66 |
67 | 2. MSBuild folder
68 |
69 | The installer install a folder call *TypeScript* to `%ProgramFile%\MSBuild\Microsoft\VisualStudio\v14.0`
70 |
71 | * Before version 2.3
72 |
73 | The folder mainly contains the TypeScript task and target file.
74 | These files include main logic to build and compile a TypeScript project.
75 |
76 | * Version 2.3 and above
77 |
78 | The folder only contains an entry point target file which although has same name as earlier version target file, it has very different contents.
79 | This new target file is what we call a stub-target file (See: Stub Target File section)
80 | It is worth noting that the installer will *NOT* install the task dll into this location anymore.
81 |
82 | # Stub Target File
83 |
84 | This file is introduced in version 2.3 and later. It replaces the original target file that has moved into *build* inside the version-numbered folder in the `%ProgramFile%/Microsoft SDKs/TypeScript` folder.
85 | The file will load a file in the *versions* folder from `%ProgramFile%/Microsoft SDKs/TypeScript`.
86 | The latest version is determined by the lexicographic ordering of the files within this folder.
87 | If the version cannot be determined, the stub target will load the version adjacent to it.
88 |
--------------------------------------------------------------------------------
/Typings-for-npm-packages.md:
--------------------------------------------------------------------------------
1 | > ### This page has moved to https://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html
2 |
--------------------------------------------------------------------------------
/Updating-TypeScript-in-Visual-Studio-2017.md:
--------------------------------------------------------------------------------
1 | In Visual Studio 2017, TypeScript updates are applied slightly differently than in Visual Studio 2015, however you can now have multiple TypeScript versions installed and choose specific versions for each of your projects.
2 | In this document, we will walk through how to manage your TypeScript version in Visual Studio 2017.
3 |
4 | ## Pre-reqs
5 |
6 | You will need Visual Studio 2017 version 15.2 or later in order to change your TypeScript version.
7 | Depending on which version you have, there are slightly different instructions for managing your TypeScript versions.
8 | That said, using the latest available version of Visual Studio will provide the best experience.
9 |
10 | ## Setting TypeScript versions in Visual Studio 2017 version 15.3
11 |
12 | In Visual Studio 2017 version 15.3 and later, the TypeScript version used is bound to individual projects.
13 |
14 | 1. Right click on the project node in Solution Explorer
15 | 2. Click **Properties**
16 | 3. Go to the **TypeScript Build** tab
17 | 4. Change **TypeScript version** to the desired version or "use latest available" to always default to the newest version installed
18 |
19 | 
20 |
21 | When setting a TypeScript version on a project, the project becomes fixed on that version.
22 | Even if a new TypeScript version becomes available through a Visual Studio update or a manual SDK download, the project will **still use the version it is fixed to**.
23 | To stay on the latest version, we encourage you to set your projects to "use latest available" as described in step 4 above.
24 |
25 | > Note! If multiple projects are loaded with different TypeScript versions set in the properties page, the **latest** TypeScript version of all versions specified will take precedence.
26 |
27 | ## Setting TypeScript versions in Visual Studio 2017 version 15.2
28 |
29 | During installation of Visual Studio 2017 version 15.2, TypeScript 2.2 will be automatically included with the Web, Node.js, Universal Windows, or Mobile JavaScript workloads. TypeScript 2.1 can also be selected from the 'Individual Components' installer page.
30 |
31 | To change TypeScript versions, change the following setting:
32 |
33 | 1. From the top menu bar, open **Tools > Options > Text Editor > JavaScript/TypeScript > IntelliSense**
34 | 2. Change **Use TypeScript version** to your desired version
35 |
36 | 
37 | (Figure 1) TypeScript Version Selection
38 |
39 | > Don't see the version you're looking for?
40 | Make sure you have downloaded the correct SDK version from the [download center](https://www.microsoft.com/en-us/download/details.aspx?id=55258) and restarted Visual Studio.
41 |
42 | To change the TypeScript version used for **building** a project, set the MSBuild property [``](http://www.typescriptlang.org/docs/handbook/compiler-options-in-msbuild.html#toolsversion) in the project file. For more information on MSBuild properties, see the TypeScript Handbook.
43 |
44 | In Visual Studio 2017 version 15.2 you are limited to setting a global TypeScript version.
45 | This means that if you have two projects that use different TypeScript compiler versions, you will have to manually toggle the setting each time you switch projects.
46 | This is not ideal, so if possible, upgrade to Visual Studio 2017 15.3 and follow the instructions below.
47 |
48 |
--------------------------------------------------------------------------------
/Useful-Links-for-TypeScript-Issue-Management.md:
--------------------------------------------------------------------------------
1 | * [Unlabelled Issues](https://github.com/Microsoft/TypeScript/issues?q=is%3Aopen+is%3Aissue+no%3Alabel): Issues which need to be analyzed and labelled
2 | * [Unlabelled VSCode Issues](https://github.com/Microsoft/TypeScript/issues?utf8=%E2%9C%93&q=is%3Aopen%20is%3Aissue%20label%3A%22VS%20Code%20Tracked%22%20-label%3A%22bug%22%20-label%3A%22Suggestion%22%20-label%3Aexternal): VSCode reported issues which need to be analyzed and labelled
3 | * [Needs Investigation Issues](https://github.com/Microsoft/TypeScript/issues?q=is%3Aopen+is%3Aissue+label%3A%22Needs+Investigation%22): Dept of unlabeled issues
4 | * [Untriaged Suggestions](https://github.com/Microsoft/TypeScript/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue+label%3A%22Suggestion%22+-label%3A%22Needs+Proposal%22+-label%3A%22Needs+More+Info%22+-label%3A%22In+Discussion%22+-label%3A%22Visual+Studio%22+-label%3A%22Revisit%22+-label%3A%22Accepting+PRs%22+-label%3A%22Committed%22): Issues with the `Suggestion` label but no sub-label
5 | * [Unplanned Bugs](https://github.com/Microsoft/TypeScript/issues?q=is%3Aopen+is%3Aissue+label%3Abug+no%3Amilestone): Issues that need to be assigned to a developer
6 | * [Bugs in 2.0.1 with No Assignee](https://github.com/Microsoft/TypeScript/issues?utf8=%E2%9C%93&q=is%3Aopen%20label%3Abug%20milestone%3A%22TypeScript%202.0.1%22%20no%3Aassignee)
7 |
8 | * [Mystery Closed Bugs](https://github.com/Microsoft/TypeScript/issues?q=is%3Aclosed+is%3Aissue+label%3Abug++-label%3AFixed+-label%3A%22By+Design%22+-label%3A%22Duplicate%22+-label%3A%22Won%27t+Fix%22): Issues that have been closed but no sub-label explaining why they were closed
9 |
10 | * [Design Meeting Docket](https://github.com/Microsoft/TypeScript/issues?q=is%3Aopen+is%3Aissue+label%3A%22in+discussion%22): Open `Suggestion` issues tagged with `In Discussion`
11 |
12 | * [Needs Proposal Review](https://github.com/Microsoft/TypeScript/issues?q=is%3Aopen+is%3Aissue+label%3A%22needs+proposal%22): Open `Suggestion` issues tagged with `Needs Proposal`
13 | * [Needs More Info Review](https://github.com/Microsoft/TypeScript/issues?q=is%3Aopen+is%3Aissue+label%3A%22needs+more+info%22): Open `Suggestion` issues tagged with `Needs More Info`
14 |
--------------------------------------------------------------------------------
/Using-TypeScript-With-ASP.NET-5.md:
--------------------------------------------------------------------------------
1 | > ### This page has moved to https://github.com/Microsoft/TypeScript-Handbook/blob/master/pages/tutorials/ASP.NET%20Core.md
--------------------------------------------------------------------------------
/Using-the-Language-Service-API.md:
--------------------------------------------------------------------------------
1 | > For an overview of the general TypeScript compiler architecture and layering, see [[Architectural Overview]]
2 |
3 | ## Overview
4 |
5 | A simple analogy for a language service object is a long-lived program, or the compilation context.
6 |
7 | ## Design Goals
8 |
9 | There are two main goals that the language service design aims to achieve:
10 |
11 | 1. **On demand processing**
12 |
13 | The language service is designed to achieve quick responses that scale with the size of the program. The only way this can be achieved is by only doing the absolute minimum work required. All language service interfaces only compute the necessary level of information needed to answer a query.
14 |
15 | For instance, a call to `getSyntacticDiagnostics` will only need the file in question to be parsed, but neither binding nor type checking will be performed in the process. A call `getCompletionsAtPosition` will only attempt to resolve declarations contributing to the type in question, but not others.
16 |
17 | 2. **Decoupling compiler pipeline phases**
18 |
19 | The language service design decouples different phases of the compiler pipeline that would normally happen in order in one shot during command-line compilation; and it allows the language service host flexibility in ordering these different phases.
20 |
21 |
22 | For instance, the language service reports diagnostics on a file per file basis, all while making a distinction between syntactic and semantic errors of each file. This ensures that the host can supply an optimal experience by retrieving syntax errors for a given file without having to pay the cost of querying other files, or performing a full semantic check. It also allows the host to skip querying for syntax errors for files that have not changed. Similarly, the language service allows for emitting a single file (`getEmitOutput`) without having to emit or even type check the whole program.
23 |
24 | ## Language Service Host
25 |
26 | The host is described by the LanguageServiceHost API, and it abstracts all interactions between the language service and the external world. The language service host defers managing, monitoring and maintaining input files to the host.
27 |
28 | The language service will only ask the host for information as part of host calls. No asynchronous events or background processing are expected. The host is expected to manage threading if needed.
29 |
30 | The host is expected to supply the full set of files comprising the context. Refer to [reference resolution in the language service](#reference-resolution-in-the-language-service) for more details.
31 |
32 | ## ScriptSnapshot
33 |
34 | A `ScriptSnapshot` represents the state of the text of an input file to the language service at a given point of time. The ScriptSnapshot is mainly used to allow for an efficient incremental parsing. A `ScriptSnapshot` is meant to answer two questions:
35 |
36 | 1. What is the current text?
37 | 2. Given a previous snapshot, what are the change ranges?
38 |
39 | Incremental parsing asks the second question to ensure it only re-parses changed regions.
40 |
41 | > For users who do not want to opt into incremental parsing, use `ts.ScriptSnapshot.fromString()`.
42 |
43 | ## Reference resolution in the language service
44 |
45 | There are two means of declaring dependencies in TypeScript: import statements, and triple-slash reference comments (`/// `). Reference resolution for a program is the process of walking the dependency graph between files, and generating a sorted list of files comprising the program.
46 |
47 | In the command-line compiler (`tsc`) this happens as part of building the program. A `createProgram` call starts with a set of root files, parses them in order, and walks their dependency declaration (both imports and triple-slash references) resolving references to actual files on disk and then pulling them into the compilation process.
48 |
49 |
51 |
52 | This work flow is decoupled in the language service into two phases, allowing the host to interject at any point and change the resolution logic if needed. It also allows the host to fully manage program structure and optimize file state change.
53 |
54 | > To resolve references originating from a file, use `ts.preProcessFile`. This method will resolve both imports and triple-slash references from a given file. Also worth noting is that this relies solely on the scanner, and does not require a full parse, so as to allow for fast context resolution which is suited to editor interactions.
55 |
56 | ## Document Registry
57 |
58 | A language service object corresponds to a single project. So if the host is handling multiple projects it will need to maintain multiple instances of the LanguageService objects; each instance of the language service holds state about the files in the context. Most of the state that a language service object holds is syntactic (text + AST). The projects can share files (at minimum, the library file `lib.d.ts`).
59 |
60 | The document registry is simply a store of SourceFile objects. If multiple language service instances share the same `DocumentRegistry` instance they will be able to share `SourceFile` objects, allowing for more efficient memory utilization.
61 |
62 |
63 |
64 | A more advanced use of the document registry is to serialize `SourceFile` objects to disk and re-hydrate them when needed.
65 |
66 | The Language service comes with a default `DocumentRegistry` implementation allowing for sharing SourceFiles between different `LanguageService` instances. Use `createDocumentRegistry` to create one, and pass it to all your `createLanguageService` calls.
67 |
--------------------------------------------------------------------------------
/Writing-Good-Design-Proposals.md:
--------------------------------------------------------------------------------
1 | ### Before You Start
2 | First, refer to the [TypeScript Design Goals](https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals) page and make sure your proposal fits within those guidelines.
3 |
4 | Next, see if there are any related [existing suggestions](https://github.com/Microsoft/TypeScript/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aopen%20label%3Asuggestion) in the issue tracker to avoid creating duplicate work.
5 |
6 | ### Defining a Scenario
7 | A good design proposal starts with a problem statement. What are users having difficulty with? What common task do we need to make easier? Who is affected? Starting with several examples that show where the current language isn't meeting the needs of programmers will help make clear what problem is being fixed. Be sure to think about what the current workarounds are.
8 |
9 | Outline the proposed change. Again, examples! You can think of TypeScript as three parts: a syntax, a type system, and a JavaScript emitter. Which parts are affected, and how? Are other language features impacted?
10 |
11 | Finally, a formal description is useful in showing that a solution has been clearly defined. Provide an exact description of the rules you're proposing. List the steps in any new algorithms that the compiler would need to implement.
12 |
13 | ### Language Feature Checklist
14 | When writing your proposal, you'll need to keep in mind how it would interact with the rest of the TypeScript language. Specific things to consider (and document) are:
15 | * Syntactic
16 | * What is the grammar of this feature?
17 | * Are there any implications for JavaScript back-compat? If so, are they sufficiently mitigated?
18 | * Does this syntax interfere with ES6 or plausible ES7 changes?
19 | * Semantic
20 | * What is an error under the proposed feature? Show many examples of both errors and non-errors
21 | * How does the feature impact subtype, supertype, identity, and assignability relationships?
22 | * How does the feature interact with generics?
23 | * Emit
24 | * What are the effects of this feature on JavaScript emit? Be specific; show examples
25 | * Does this emit correctly in the presence of variables of type ‘any’? Features cannot rely on runtime type information
26 | * What are the impacts to declaration file (.d.ts) emit?
27 | * Does this feature play well with external modules?
28 | * Compatibility
29 | * Is this a breaking change from the 1.0 compiler? Changes of this nature require strong justification
30 | * Is this a breaking change from JavaScript behavior? TypeScript does not alter JavaScript expression semantics, so the answer here must be “no”
31 | * Is this an incompatible implementation of a future JavaScript (i.e. ES6/ES7/later) feature?
32 | * Other
33 | * Can the feature be implemented without negatively affecting compiler performance?
34 | * What impact does it have on tooling scenarios, such as member completion and signature help in editors?
35 |
--------------------------------------------------------------------------------
/Writing-a-Language-Service-Plugin.md:
--------------------------------------------------------------------------------
1 | # Writing a TypeScript Language Service Plugin
2 |
3 | In TypeScript 2.2 and later, developers can enable *language service plugins* to augment the TypeScript code editing experience. The purpose of this guide is to help you write your own plugin.
4 |
5 | ## What's a Language Service Plugin?
6 |
7 | TypeScript Language Service Plugins ("plugins") are for changing the *editing experience* only. The core TypeScript language remains the same. Plugins can't add new language features such as new syntax or different typechecking behavior, and plugins aren't loaded during normal commandline typechecking or emitting, (so are not loaded by `tsc`).
8 |
9 | Instead, plugins are for augmenting the editing experience. Some examples of things plugins might do:
10 | * Provide errors from a linter inline in the editor
11 | * Filter the completion list to remove certain properties from `window`
12 | * Redirect "Go to definition" to go to a different location for certain identifiers
13 | * Enable new errors or completions in string literals for a custom templating language
14 |
15 | Examples of things language plugins cannot do:
16 | * Add new custom syntax to TypeScript
17 | * Change how the compiler emits JavaScript
18 | * Customize the type system to change what is or isn't an error when running `tsc`
19 |
20 | Developers using the plugin will `npm install --save-dev your_plugin_name` and edit their `tsconfig.json` file to enable your plugin.
21 |
22 | ## Kickstart your plugin
23 |
24 | There is a template repo which shows a working development environment for a TSServer Plugin here: https://github.com/orta/TypeScript-TSServer-Plugin-Template
25 |
26 | ## Overview: Writing a Simple Plugin
27 |
28 | Let's write a simple plugin. Our plugin will remove a user-configurable list of property names from the completion list. You might use this sort of plugin on your team to help remind you which APIs are 'banned' (for example, using the `caller` property of `function` is discouraged).
29 |
30 | ### Setup and Initialization
31 |
32 | When your plugin is loaded, it's first initialized as a factory function with its first parameter set to `{typescript: ts}`. It's important to use *this* value, rather than the imported `ts` module, because any version of TypeScript might be loaded by tsserver. If you use any other object, you'll run into compatibility problems later because enum values may change between versions.
33 |
34 | Here's the minimal code that handles this injected `ts` value:
35 | ```ts
36 | function init(modules: { typescript: typeof import("typescript/lib/tsserverlibrary") }) {
37 | const ts = modules.typescript;
38 | /* More to come here */
39 | }
40 |
41 | export = init;
42 | ```
43 |
44 | ### Decorator Creation
45 |
46 | TypeScript Language Service Plugins use the [Decorator Pattern](https://en.wikipedia.org/wiki/Decorator_pattern) to "wrap" the main TypeScript Language Service. When your plugin is initialized, it will be given a Language Service instance to wrap, and should return a new decorator wrapping this instance. This is exposed through the `create` function returned from your outer factory function.
47 |
48 | Let's fill in some more code to properly set up a decorator:
49 | ```ts
50 | function init(modules: { typescript: typeof import("typescript/lib/tsserverlibrary") }) {
51 | const ts = modules.typescript;
52 |
53 | function create(info: ts.server.PluginCreateInfo) {
54 | // Set up decorator object
55 | const proxy: ts.LanguageService = Object.create(null);
56 |
57 | for (let k of Object.keys(info.languageService) as Array) {
58 | const x = info.languageService[k]!;
59 | // @ts-expect-error - JS runtime trickery which is tricky to type tersely
60 | proxy[k] = (...args: Array<{}>) => x.apply(info.languageService, args);
61 | }
62 |
63 | return proxy;
64 | }
65 |
66 | return { create };
67 | }
68 |
69 | export = init;
70 | ```
71 |
72 | This sets up a "pass-through" decorator that invokes the underlying language service for all methods.
73 |
74 | ### Enabling a plugin
75 |
76 | To enable this plugin, users will add an entry to the `plugins` list in their `tsconfig.json` file:
77 | ```json
78 | {
79 | "compilerOptions": {
80 | "noImplicitAny": true,
81 | "plugins": [{ "name": "sample-ts-plugin" }]
82 | }
83 | }
84 | ```
85 |
86 | This name can only be an NPM package name.
87 |
88 | ### Customizing Behavior
89 |
90 | Let's modify the above pass-through plugin to add some new behavior.
91 |
92 | We'll change the `getCompletionsAtPosition` function to remove certain entries named `caller` from the completion list:
93 | ```ts
94 | // Remove specified entries from completion list
95 | proxy.getCompletionsAtPosition = (fileName, position, options) => {
96 | const prior = info.languageService.getCompletionsAtPosition(fileName, position, options);
97 | prior.entries = prior.entries.filter(e => e.name !== "caller");
98 | return prior;
99 | };
100 | ```
101 |
102 | ## Handling User Configuration
103 |
104 | Users can customize your plugin behavior by providing additional data in their `tsconfig.json` file. Your plugin is given its enabling entry from the `tsconfig.json` file in the `info.config` property.
105 |
106 | Let's allow the user to customize the list of names to remove from the completion list:
107 | ```ts
108 | function create(info: ts.server.PluginCreateInfo) {
109 | // Get a list of things to remove from the completion list from the config object.
110 | // If nothing was specified, we'll just remove 'caller'
111 | const whatToRemove: string[] = info.config.remove || ["caller"];
112 |
113 | const proxy: ts.LanguageService = Object.create(null);
114 | // ... (set up decorator here) ...
115 |
116 | // Remove specified entries from completion list
117 | proxy.getCompletionsAtPosition = (fileName, position, options) => {
118 | const prior = info.languageService.getCompletionsAtPosition(
119 | fileName,
120 | position,
121 | options
122 | );
123 | prior.entries = prior.entries.filter(e => whatToRemove.indexOf(e.name) < 0);
124 | return prior;
125 | };
126 |
127 | return proxy;
128 | }
129 | ```
130 |
131 | The new `tsconfig.json` file might look like this:
132 | ```json
133 | {
134 | "compilerOptions": {
135 | "noImplicitAny": true,
136 | "plugins": [{
137 | "name": "sample-ts-plugin",
138 | "remove": ["caller", "callee", "getDay"]
139 | }]
140 | }
141 | }
142 | ```
143 |
144 | ## Debugging
145 |
146 | You'll probably want to add some logging to your plugin to help you during development. The TypeScript Server Log allows plugins to write to a common log file.
147 |
148 | ### Setting up TypeScript Server Logging
149 |
150 | Your plugin code runs inside the TypeScript Server process. Its logging behavior can be enabled by setting the `TSS_LOG` environment variable. To log to a file, set `TSS_LOG` to:
151 | ```
152 | -logToFile true -file C:\SomeFolder\MyTypeScriptLog.txt -level verbose
153 | ```
154 | Ensure that the containing directory (`C:\SomeFolder` in this example) exists and is writable.
155 |
156 | ### Logging from your plugin
157 |
158 | You can write to this log by calling into the TypeScript project's logging service:
159 | ```ts
160 | function create(info: ts.server.PluginCreateInfo) {
161 | info.project.projectService.logger.info(
162 | "I'm getting set up now! Check the log for this message."
163 | );
164 | }
165 | ```
166 |
167 | ## Putting it all together
168 |
169 | ```ts
170 | function init(modules: { typescript: typeof import("typescript/lib/tsserverlibrary") }) {
171 | const ts = modules.typescript;
172 |
173 | function create(info: ts.server.PluginCreateInfo) {
174 | // Get a list of things to remove from the completion list from the config object.
175 | // If nothing was specified, we'll just remove 'caller'
176 | const whatToRemove: string[] = info.config.remove || ["caller"];
177 |
178 | // Diagnostic logging
179 | info.project.projectService.logger.info(
180 | "I'm getting set up now! Check the log for this message."
181 | );
182 |
183 | // Set up decorator object
184 | const proxy: ts.LanguageService = Object.create(null);
185 | for (let k of Object.keys(info.languageService) as Array) {
186 | const x = info.languageService[k]!;
187 | // @ts-expect-error - JS runtime trickery which is tricky to type tersely
188 | proxy[k] = (...args: Array<{}>) => x.apply(info.languageService, args);
189 | }
190 |
191 | // Remove specified entries from completion list
192 | proxy.getCompletionsAtPosition = (fileName, position, options) => {
193 | const prior = info.languageService.getCompletionsAtPosition(fileName, position, options);
194 | if (!prior) return
195 |
196 | const oldLength = prior.entries.length;
197 | prior.entries = prior.entries.filter(e => whatToRemove.indexOf(e.name) < 0);
198 |
199 | // Sample logging for diagnostic purposes
200 | if (oldLength !== prior.entries.length) {
201 | const entriesRemoved = oldLength - prior.entries.length;
202 | info.project.projectService.logger.info(
203 | `Removed ${entriesRemoved} entries from the completion list`
204 | );
205 | }
206 |
207 | return prior;
208 | };
209 |
210 | return proxy;
211 | }
212 |
213 | return { create };
214 | }
215 |
216 | export = init;
217 | ```
218 |
219 | ## Testing Locally
220 |
221 | To locally test your plugin, set up a sample project and use a `file:` dependency ( e.g. `"tsserver-plugin": "file:.."`) to link your plugin via the module name in the tsconfig.json file. For example:
222 |
223 | ```
224 | your_plugin/index.ts
225 | your_plugin/index.js (compiled by tsc)
226 | your_plugin/sample_project/package.json
227 | your_plugin/sample_project/tsconfig.json
228 | ```
229 |
230 | where `your_plugin/sample_project/package.json` contains
231 |
232 | ```json
233 | {
234 | "name": "sample_project",
235 | "dependencies": {
236 | "your_plugin": "file:..",
237 | "typescript": "^4.4.3"
238 | }
239 | }
240 |
241 | ```
242 |
243 | and `your_plugin/sample_project/tsconfig.json` contains
244 |
245 | ```json
246 | {
247 | "compilerOptions": {
248 | "plugins": [{
249 | "name": "your_plugin",
250 | }]
251 | }
252 | }
253 | ```
254 |
255 | Alternatively, you can test your plugin similarly to how you would test other node modules. To set
256 | up a sample project where you can easily test plugin changes:
257 |
258 | * Run `npm link` from your plugin directory
259 | * In your sample project, run `npm link your_plugin_name`
260 | * Add an entry to the `plugins` field of the `tsconfig.json`
261 | * Rebuild your plugin and restart your editor to pick up code changes
262 |
263 | **Note**: If you're using Visual Studio Code, you'll have to use the first approach above, with a
264 | path to the module, or run the "TypeScript: Select TypeScript Version" command and choose "Use
265 | Workspace Version", or click the version number between "TypeScript" and 😃 in the lower-right
266 | corner. Otherwise, VS Code will not be able to find your plugin.
267 |
268 | ## Real-world Plugins
269 |
270 | Some other TypeScript Language Service Plugin implementations you can look at for reference:
271 |
272 | * https://github.com/angular/angular/blob/master/packages/language-service/src/ts_plugin.ts
273 | * https://github.com/Quramy/ts-graphql-plugin
274 | * https://github.com/styled-components/typescript-styled-plugin
275 | * https://github.com/xialvjun/ts-sql-plugin
276 | * https://github.com/HearTao/ts-string-literal-enum-plugin
277 | * https://github.com/ngnijland/typescript-todo-or-die-plugin
278 | * https://github.com/mdx-js/mdx-analyzer/tree/main/packages/typescript-plugin
279 | * https://github.com/sveltejs/language-tools/tree/master/packages/typescript-plugin
280 | * https://github.com/vuejs/language-tools/tree/master/packages/typescript-plugin
281 | * https://github.com/withastro/language-tools/blob/main/packages/ts-plugin/README.md
282 |
--------------------------------------------------------------------------------
/_Footer.md:
--------------------------------------------------------------------------------
1 | ### Want to contribute to this Wiki?
2 |
3 | [Fork it and send a pull request.](https://github.com/Microsoft/TypeScript-wiki)
4 |
--------------------------------------------------------------------------------
/_Sidebar.md:
--------------------------------------------------------------------------------
1 | ## [User documentation](https://www.typescriptlang.org/)
2 |
3 | **News**
4 | * [[Roadmap]]
5 | * [[Breaking Changes]]
6 | * [[API Breaking Changes]]
7 |
8 | **Debugging TypeScript**
9 | * [[Performance]]
10 | * [[Performance-Tracing]]
11 | * [[Debugging-Language-Service-in-VS-Code]]
12 | * [[Getting-logs-from-TS-Server-in-VS-Code]]
13 | * [[JavaScript-Language-Service-in-Visual-Studio]]
14 | * [[Providing-Visual-Studio-Repro-Steps]]
15 |
16 | **Contributing to TypeScript**
17 | * [[Contributing to TypeScript]]
18 | * [[TypeScript Design Goals]]
19 | * [[Coding Guidelines]]
20 | * [[Useful Links for TypeScript Issue Management]]
21 | * [[Writing Good Design Proposals]]
22 | * [Compiler Repo Notes](https://github.com/microsoft/TypeScript-Compiler-Notes/)
23 | * [Deployment](https://github.com/microsoft/TypeScript/wiki/TypeScript-Deployment)
24 |
25 | **Building Tools for TypeScript**
26 | * [[Architectural Overview]]
27 | * [[Using the Compiler API]]
28 | * [[Using the Language Service API]]
29 | * [[Standalone Server (tsserver)]]
30 | * [[TypeScript MSBuild In Depth]]
31 | * [[Debugging Language Service in VS Code]]
32 | * [[Writing a Language Service Plugin]]
33 | * [[Docker Quickstart]]
34 |
35 | **FAQs**
36 | * [[FAQ]]
37 | * [[FAQs for API Consumers]]
38 |
39 | **The Main Repo**
40 | * [[Triggering TypeScript Bot]]
41 | * [[Tooling on the Compiler Repo]]
42 |
--------------------------------------------------------------------------------
/aspnet-screenshots/add-tsconfig.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/aspnet-screenshots/add-tsconfig.png
--------------------------------------------------------------------------------
/aspnet-screenshots/compile-on-save.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/aspnet-screenshots/compile-on-save.png
--------------------------------------------------------------------------------
/aspnet-screenshots/new-project.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/aspnet-screenshots/new-project.png
--------------------------------------------------------------------------------
/aspnet-screenshots/postbuild.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/aspnet-screenshots/postbuild.png
--------------------------------------------------------------------------------
/aspnet-screenshots/project.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/aspnet-screenshots/project.png
--------------------------------------------------------------------------------
/aspnet-screenshots/virtual-project.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/aspnet-screenshots/virtual-project.png
--------------------------------------------------------------------------------
/codebase/compiler/Codebase-Compiler-Emitter.md:
--------------------------------------------------------------------------------
1 | ## Emitter
2 |
3 | The emitter is a tree based syntax emitter. It works by going through the TypeScript AST for a program and
4 | emitting source code as it is pipelined.
5 |
6 | The emitter itself is "dumb" in the sense that it doesn't contain logic outside of printing whatever AST it is
7 | given. So, it's possible that a bug in emission is actually that the AST isn't set up the way that you'd like it.
8 |
9 | ### Outfile
10 |
11 | Creating a single file which represents many is done by creating a `SyntaxKind.Bundle`. Printing happens in
12 | [`function writeBundle(`][0]. There are `prepends` which I don't understand, and then each sourcefile is is
13 | printed.
14 |
15 | ### Printer
16 |
17 | The printer is a part of the emitter, you create one with [`createPrinter`][1], then start calling [`print`][2]
18 | with an AST node on it. This adds the node via a [pipeline][3]:
19 |
20 | ```ts
21 | const enum PipelinePhase {
22 | Notification,
23 | Substitution,
24 | Comments,
25 | SourceMaps,
26 | Emit,
27 | }
28 | ```
29 |
30 | With the word to start emitting through the AST in [`pipelineEmitWithHint`][4]. There is a hint option which can
31 | be used to force the emit type.
32 |
33 | ## Post Processing via Transformers
34 |
35 | The process of changing your AST into the expected JS or TS happens the emitter compiler transformers. There is a
36 | full step
37 |
38 | Emitting a declaration file is a multi-step process. It goes through the above emitter of its AST, but then _also_
39 | goes through a
40 |
41 |
42 | [0]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/compiler/emitter.ts#L1041
43 | [0]:
44 | [1]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/compiler/emitter.ts#L852
45 | [1]:
46 | [2]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/compiler/emitter.ts#L1129
47 | [2]:
48 | [3]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/compiler/emitter.ts#L844
49 | [3]:
50 | [3]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/compiler/emitter.ts#L1270
51 | [3]:
52 |
53 |
--------------------------------------------------------------------------------
/codebase/compiler/Codebase-Compiler-FAQ.md:
--------------------------------------------------------------------------------
1 | # Frequently Asked Questions
2 |
3 | ## How can I find out if a type is `number[]`?
4 |
5 | ```ts
6 | getElementTypeOfArrayType(t) === numberType
7 | ```
8 |
9 | `getElementTypeOfArrayType` returns undefined if `t` is not an array type.
10 | Use `isArrayType` or `isArrayLikeType` if that's all you need to know.
11 |
12 | ## How can I delete nodes in a transformer?
13 |
14 | Probably you return `undefined` instead of a new or existin node, but look at src/compiler/transformers/ts.ts.
15 | Deleting type annotations is its main job.
16 |
17 |
--------------------------------------------------------------------------------
/codebase/compiler/Codebase-Compiler-Parser.md:
--------------------------------------------------------------------------------
1 |
2 | [0]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/compiler/program.ts#L1926# Parser
3 |
4 | At a measly 8k lines long, the Parser is responsible for controlling a scanner (or two) and turning the output
5 | tokens from the scanner into an AST as the canonical representation of the source file.
6 |
7 | ## JSDoc
8 |
9 | ## Context
10 |
11 | Because the parser itself is effectively a state machine which creates nodes from scanning text there is some
12 | reasonable dancing
13 |
14 |
15 |
16 | [0]:
17 | [4]: GLOSSARY.md#statements
18 |
19 |
20 |
21 | `
22 |
--------------------------------------------------------------------------------
/codebase/compiler/Codebase-Compiler-Scanner.md:
--------------------------------------------------------------------------------
1 | # Scanner
2 |
3 | One of the smallest parts of the compiler's critical path to AST then type-checking. It exists to create a stream
4 | of syntax tokens for use by another object. The scanner gets most of its usage via a [parser][0] instance.
5 |
6 | ## Overview
7 |
8 | You create a Scanner instance via [`createScanner`][1], there are two main modes of scanning: Standard and JSX.
9 | Then there are specific functions for scanning inside JSDoc comments.
10 |
11 | First you set the text of a scanner to be your JS source code via [`setText`][2], this takes the source code and
12 | an optional start and end range in which you want to scan. This range is an important part of what keeps
13 | TypeScript's server mode fast via [incremental parsing][3].
14 |
15 | At a high level, the scanner works by a having another object call [`scanner.scan`][4] this:
16 |
17 | - Pulls out the character at the current position (`pos`) in the text
18 | - Runs a very big switch statement against known characters which start syntax
19 | - Then move look forwards till the end of that list of chars to decode if it's what we think it is. here's an
20 | example of what happens when [the character found][5] is a `!`:
21 |
22 | ```ts
23 | case CharacterCodes.exclamation:
24 | // Look to see if it's "!="
25 | if (text.charCodeAt(pos + 1) === CharacterCodes.equals) {
26 | // Also check if it's "!=="
27 | if (text.charCodeAt(pos + 2) === CharacterCodes.equals) {
28 | // for !== move the position forwards to the end of the symbol
29 | // then set the token
30 | return pos += 3, token = SyntaxKind.ExclamationEqualsEqualsToken;
31 | }
32 | // Move it two, set the token
33 | return pos += 2, token = SyntaxKind.ExclamationEqualsToken;
34 | }
35 |
36 | // Move forwards one character and set the token
37 | pos++;
38 | return token = SyntaxKind.ExclamationToken;
39 | ```
40 |
41 | - A `SyntaxKind` is returned from [`scan`][4] and it's up to the scanner owner to do work with those tokens. The
42 | scanner keeps track of a few useful values for that:
43 |
44 | - `getStartPos` - where the token was started including preceding whitespace
45 | - `getTextPos` - the end position of the current token
46 | - `getTokenText` - the text between the token start and end
47 | - `getTokenValue` - some syntax contains a value which can be represented as a string, a good example is
48 | literally a string. The `"` or `'` are not included in the value.
49 |
50 |
51 | ## Full Start/Token Start
52 |
53 | Tokens themselves have what we call a "full start" and a "token start". The "token start" is the more natural version, which is the position in the file where the text of a token begins. The "full start" is the point at which the scanner began scanning since the last significant token. When concerned with trivia, we are often more concerned with the full start.
54 |
55 | Function | Description
56 | ---------|------------
57 | `ts.Node.getStart` | Gets the position in text where the first token of a node started.
58 | `ts.Node.getFullStart` | Gets the position of the "full start" of the first token owned by the node.
59 |
60 |
61 | ## Trivia
62 |
63 | When creating a scanner you get to choose whether whitespace should be returned in the stream of tokens. This is
64 | nearly always off, but it is used inside the [formatter][6] and for syntax highlighting via the TSServer via a
65 | [classifier][7].
66 |
67 | Syntax trivia represent the parts of the source text that are largely insignificant for normal understanding of the code, such as whitespace, comments, and even conflict markers.
68 |
69 | Because trivia are not part of the normal language syntax (barring ECMAScript ASI rules) and can appear anywhere between any two tokens, they are not included in the syntax tree. Yet, because they are important when implementing a feature like refactoring and to maintain full fidelity with the source text, they are still accessible through our APIs on demand.
70 |
71 | Because the `EndOfFileToken` can have nothing following it (neither token nor trivia), all trivia naturally precedes some non-trivia token, and resides between that token's "full start" and the "token start"
72 |
73 | It is a convenient notion to state that a comment "belongs" to a `Node` in a more natural manner though. For instance, it might be visually clear that the `genie` function declaration owns the last two comments in the following example:
74 |
75 | ```TypeScript
76 | var x = 10; // This is x.
77 |
78 | /**
79 | * Postcondition: Grants all three wishes.
80 | */
81 | function genie([wish1, wish2, wish3]: [Wish, Wish, Wish]) {
82 | while (true) {
83 | }
84 | } // End function
85 | ```
86 |
87 | This is despite the fact that the function declaration's full start occurs directly after `var x = 10;`.
88 |
89 | We follow [Roslyn's notion of trivia ownership](https://github.com/dotnet/roslyn/wiki/Roslyn%20Overview#syntax-trivia) for comment ownership. In general, a token owns any trivia after it on the same line up to the next token. Any comment after that line is associated with the following token. The first token in the source file gets all the initial trivia, and the last sequence of trivia in the file is tacked onto the end-of-file token, which otherwise has zero width.
90 |
91 | For most basic uses, comments are the "interesting" trivia. The comments that belong to a Node which can be fetched through the following functions:
92 |
93 | Function | Description
94 | ---------|------------
95 | `ts.getLeadingCommentRanges` | Given the source text and position within that text, returns ranges of comments between the first line break following the given position and the token itself (probably most useful with `ts.Node.getFullStart`).
96 | `ts.getTrailingCommentRanges` | Given the source text and position within that text, returns ranges of comments until the first line break following the given position (probably most useful with `ts.Node.getEnd`).
97 |
98 | As an example, imagine this portion of a source file:
99 |
100 | ```TypeScript
101 | debugger;/*hello*/
102 | //bye
103 | /*hi*/ function
104 | ```
105 |
106 | The full start for the `function` keyword begins at the `/*hello*/` comment, but `getLeadingCommentRanges` will only return the last 2 comments:
107 |
108 | ```
109 | d e b u g g e r ; / * h e l l o * / _ _ _ _ _ [CR] [NL] _ _ _ _ / / b y e [CR] [NL] _ _ / * h i * / _ _ _ _ f u n c t i o n
110 | ↑ ↑ ↑ ↑ ↑
111 | full start look for first comment second comment token start
112 | leading comments
113 | starting here
114 | ```
115 |
116 | Appropriately, calling `getTrailingCommentRanges` on the end of the debugger statement will extract the `/*hello*/` comment.
117 |
118 | In the event that you are concerned with richer information of the token stream, `createScanner` also has a `skipTrivia` flag which you can set to `false`, and use `setText`/`setTextPos` to scan at different points in a file.
119 |
120 |
121 | ## JSX
122 |
123 | Some of the more complicated aspects of JSX support is mostly handled back in [the parser][0], however JSX support
124 | in the scanner [uses specific syntax tokens][8].
125 |
126 | ## Flags
127 |
128 | One way for the scanner to keep track of scan issues, or internal state is [via `TokenFlags`][9]. Any example of
129 | this is in scanning a number. TypeScript supports underscores in numbers `100_000`, when scanning a number literal
130 | if it detects a `CharacterCodes._` then the flag `TokenFlags.ContainsSeparator` is set and later on that is used
131 | to ensure the `tokenValue` is set correctly.
132 |
133 | ## Rescanning
134 |
135 | Because the scanner is only interested in passing out tokens as it sees them, it doesn't really have a memory of
136 | previous tokens. This means that occasionally the controlling object will need to rewind and re-run the scanner
137 | with a different type of context. This is called rescanning.
138 |
139 | ## Example code
140 |
141 | [Here's a scanner playground](https://5d39df23407c626e65aee7ef--ts-scanner-tokens.netlify.com) - adding TypeScript
142 | will show you the tokens generated by a single scanner. It's worth noting that this doesn't represent that
143 | _actual_ results of the scanner when using TypeScript, because the parser controls re-scanning and this playground
144 | doesn't do that.
145 |
146 |
147 | [0]: ./parser.md
148 | [1]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/compiler/scanner.ts#L929
149 | [1]:
150 | [2]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/compiler/scanner.ts#L2551
151 | [2]:
152 | [3]: GLOSSARY.md#incremental-parsing
153 | [4]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/compiler/scanner.ts#L1609
154 | [4]:
155 | [5]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/compiler/scanner.ts#L1681
156 | [5]:
157 | [6]: ./formatter.md
158 | [7]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/services/classifier.ts#L3
159 | [7]:
160 | [8]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/compiler/types.ts#L709
161 | [8]:
162 | [9]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/compiler/types.ts#L2159
163 | [9]:
164 |
165 |
--------------------------------------------------------------------------------
/codebase/compiler/Codebase-Compiler-Services.md:
--------------------------------------------------------------------------------
1 | ## Services
2 |
3 | `services` is effectively the place where all the IDE and TS meet. It it a series of files which power the
4 | LSP-like TSServer.
5 |
6 | The services are APIs are used by TSServer, which creates a `ts.server` SessionClient in `src/harness/client.ts`
7 | (it seems most of the `class`es in the compiler live in the server/services space. Maybe a by-product of working
8 | tightly with the VS Code team? )
9 |
--------------------------------------------------------------------------------
/codebase/compiler/Codebase-Compiler-Types.md:
--------------------------------------------------------------------------------
1 | # Type Hierarchy
2 |
3 | Root class: `Type`
4 |
5 | ### How are properties stored and found on a type?
6 |
7 | `checkPropertyAccessExpressionOrQualifiedName`
8 |
9 | ### getDeclaredTypeOfSymbol vs getTypeOfSymbol
10 |
11 | The problem is that symbols can have both types and values associated with them:
12 |
13 | ```ts
14 | type A = number
15 | const A = "do not do this"
16 | ```
17 |
18 | And the compiler needs a way to get the type of both the type and the const.
19 | So it uses `getDeclaredTypeOfSymbol` for types and `getTypeOfSymbol[AtLocation]` for values:
20 |
21 | ```ts
22 | getDeclaredTypeOfSymbol(A) == number
23 | getTypeOfSymbol(A) == string
24 | ```
25 |
26 | Confusingly, classes (and enums and aliases) declare both a type and a value, so, a tiny bit arbitrarily, the instance side is the type and the static side is the value:
27 |
28 | ```ts
29 | class C {
30 | m() { }
31 | static s() { }
32 | }
33 | getTypeOfSymbol() == { new(): C, s(): void } == typeof C
34 | getDeclaredTypeOfSymbol() == { m(): void } == C
35 | ```
36 |
37 | This kind of makes sense when you think about that C actually does when executed: it defines a value that is constructable.
38 | This leads to the "deconstructed class" pattern used in tricky situations, for example:
39 |
40 | ``` ts
41 | interface C {
42 | m(): void
43 | }
44 | var C: {
45 | new(): C
46 | s: void
47 | }
48 | ```
49 |
50 | Again, it's a tiny bit arbitrary to choose the static side as the value, since ultimately you get a value from calling new C() too.
51 | But the deconstructed class pattern shows that you can get away with writing just a type for the instance side, whereas you must write a value for the static side.
52 |
53 |
54 |
55 | [1]:
58 |
--------------------------------------------------------------------------------
/codebase/compiler/Codebase-Compiler-Utils.md:
--------------------------------------------------------------------------------
1 | ### Util Functions
2 |
3 | Some essentials:
4 |
5 | - [`findAncestor`][0]
6 |
7 | > Iterates through the parent chain of a node and performs the callback on each parent until the callback returns
8 | > a truthy value, then returns that value.
9 | >
10 | > If no such value is found, it applies the callback until the parent pointer is undefined or the callback returns
11 | > "quit" At that point findAncestor returns undefined.
12 |
13 | Basically looks up the AST until it finds something which passes.
14 |
--------------------------------------------------------------------------------
/codebase/services/Codebase-Services-Completions.md:
--------------------------------------------------------------------------------
1 | # Completions
2 |
3 |
4 | Completions for TypeScript and JavaScript are provided by TypeScript's language service.
5 | When you are in the middle of typing something in an editor (or if you hit Ctrl + Space in VSCode), the editor sends a request to the TypeScript language service.
6 | Completions is responsible for answering that request with suggestions to *complete* what you are typing.
7 |
8 |
9 | ## Overview
10 |
11 | Most of the implementation lives in the `src/services/completions.ts` file, and there are several steps the implementation goes through to answer a completion request.
12 |
13 | The entry point into completions is `getCompletionsAtPosition()`.
14 | As the name suggests, this function takes a `SourceFile` and a `position` as arguments (among other things), and it returns a [`CompletionInfo`](https://github.com/microsoft/TypeScript/blob/404a7d602df9c19d98d49e6a6bf2295e423be676/src/services/types.ts?#L1172-L1191) object with completions for that specific position.
15 |
16 | `CompletionInfo` has a few different properties, but we're mainly interested in the `entries: CompletionEntry[]` property, because a [`CompletionEntry`](https://github.com/microsoft/TypeScript/blob/404a7d602df9c19d98d49e6a6bf2295e423be676/src/services/types.ts?#L1220-L1249) encodes the suggestions returned.
17 |
18 |
19 | ### Completion entry
20 |
21 | Some `CompletionEntry` properties and what they mean:
22 |
23 | * **name**: the name of that completion entry. Usually if the completion is for an identifier/keyword named `foo`, then the name of the entry is also going to be `foo`.
24 | * **insertText**: the text that is going to be inserted in the file, at the completion position, when the user accepts the suggestion corresponding to this completion entry.
25 | `insertText` is optional, and if it is not present, then `name` is the text that is inserted instead.
26 | * **isSnippet**: if this is true, then this completion entry is a snippet, and `insertText` is a snippet text.
27 | e.g.:
28 | A completion snippet for declaring a method `foo`, with a tab stop (`${0}`) in its body:
29 | ```ts
30 | {
31 | isSnippet: true,
32 | insertText: "foo() { ${0} }",
33 | }
34 | ```
35 | becomes this in VSCode, when accepted (note the cursor position):
36 | 
37 | For more on snippets, see [Snippets in Visual Studio Code](https://code.visualstudio.com/docs/editor/userdefinedsnippets).
38 | * **replacementSpan**: the span (i.e. a continuous range) of the source file that is going to be *replaced* by the text inserted by this completion. It is optional, so we only need to provide this if we want to override the *default* replacement span for this completion entry.
39 | * **hasAction**: whether that completion requires additional actions if it is accepted. For instance, a completion might insert variables that need to be imported, so if that completion is accepted, it needs an additional action of inserting import statements.
40 |
41 | ## Implementation
42 |
43 | `getCompletionsAtPosition()` goes through a lot of steps and additional function calls before returning a `CompletionInfo` response.
44 | Roughly the steps are:
45 | 1. call `getCompletionData` to gather the data needed to construct a `CompletionInfo`.
46 | `getCompletionData`'s returns data including a **list of symbols** for things (e.g. variables, properties) we may want to offer for completions.
47 | 2. We call the appropriate function for transforming the completion data into completion info.
48 | The exact function called depends on the the kind of data returned by `getCompletionData`, which can be:
49 | * `JSDoc`: JSDoc-specific completion data,
50 | * `Keywords`: keyword completion data,
51 | * `Data`: general data not falling into the above categories (aka everything else).
52 |
53 | If the data is of jsdoc kind, then we call `jsdocCompletionInfo`, if it is keyword data we call `specificKeywordCompletionInfo`.
54 | Most importantly, though, when we have the general kind of data, we proceed with **calling `completionInfoFromData`**.
55 | This is the flow you want to look at most of the time, so let's assume we are following this general flow.
56 | 3. `completionInfoFromData` is called with the data we got from `getCompletionData`.
57 | Mainly, it calls `getCompletionEntriesFromSymbols` to construct completion entries from the symbols obtained in `getCompletionData`.
58 |
59 | ### `getCompletionData`
60 |
61 | Step one is to grab [a `CompletionData`][1] via [`getCompletionData`][2]. This function tries to find a context
62 | token which first looks forwards, and then try find a `contextToken`. This is generally the preceding token to
63 | your cursor, as that tends to be the most important thing when deciding what to show next. This takes into account
64 | things like `x.y` and `y?.y` by diving deeper into preceding identifier.
65 |
66 | This dive to find a "responsible" item for a completion request called `node` in the code.
67 |
68 | Next it goes through the following checks for a set of completions.
69 | TODO: continue this.
70 |
71 | ### [`getCompletionEntriesFromSymbols`]((https://github.com/Microsoft/TypeScript/blob/340f81035ff1d753e6a1f0fedc2323d169c86cc6/src/services/completions.ts#L305))
72 |
73 | Some completion scenarios require doing special work when transforming a symbol into a completion entry.
74 | That special work is done here, in `getCompletionEntriesFromSymbols`, when we call `createCompletionEntry`.
75 |
76 | As an example, let's walk through [class member snippet completions](https://github.com/microsoft/TypeScript/pull/46370), a completion scenario that suggests whole class member declarations (i.e. method and property declarations).
77 | In `createCompletionEntry`, we get the symbol for a class member, say a method `foo`, that we want to offer as a completion. First, we detect that this symbol is for a class member (i.e. method `foo`'s symbol).
78 | Then, to turn that symbol into a completion entry, we have to figure out what the `insertText` for the entry must be.
79 | For method `foo`'s completion entry, we decide the `insertText` is going to be the declaration for method `foo`, something like:
80 | ```ts
81 | foo(x: string): number {
82 | // empty implementation
83 | }
84 | ```
85 | So, to get that custom `insertText`, `createCompletionEntry` calls [`getEntryForMemberCompletion`](https://github.com/microsoft/TypeScript/blob/404a7d602df9c19d98d49e6a6bf2295e423be676/src/services/completions.ts#L857).
86 |
87 | Another scenario that works similarly is import completions: in `createCompletionEntry`, we call [`getInsertTextAndReplacementSpanForImportCompletion`](https://github.com/microsoft/TypeScript/blob/404a7d602df9c19d98d49e6a6bf2295e423be676/src/services/completions.ts#L1118) to get the custom `insertText` for a completion for importing a symbol, for instance `import { foo } from "foo"`.
88 |
89 | ## String Literal Completions
90 |
91 | E.g. are you inside a string and asking for completions? TS differentiates between reference comments
92 | ([triple slash](https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html)):
93 |
94 | 
95 |
96 | And strings as a part of the AST. These have a
97 | [few](https://github.com/Microsoft/TypeScript/blob/340f81035ff1d753e6a1f0fedc2323d169c86cc6/src/services/stringCompletions.ts#L103)
98 | different uses:
99 |
100 | - They could be path references
101 | - They could be module references
102 | - They could be indexed keys from an object
103 | - They could be parts of a union object
104 |
105 | ####
106 |
107 |
108 | [1]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/services/completions.ts#L1525
109 | [1]:
110 | [2]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/services/completions.ts#L1618
111 | [2]:
112 |
113 |
--------------------------------------------------------------------------------
/codebase/services/Codebase-Services-TextChanges.md:
--------------------------------------------------------------------------------
1 | # Text Changes
2 |
3 | The majority of this file is devoted to a class called the [`ChangeTracker`][0]. This class is nearly always
4 | created via `ChangeTracker.with` where you would give it a context object.
5 |
6 | Here is an example context object:
7 |
8 | ```ts
9 | {
10 | cancellationToken:CancellationTokenObject {cancellationToken: TestCancellationToken}
11 | errorCode:2304
12 | formatContext:Object {options: Object, getRule: }
13 | host:NativeLanguageServiceHost {cancellationToken: TestCancellationToken, settings: Object, sys: System, …}
14 | preferences:Object {}
15 | program:Object {getRootFileNames: , getSourceFile: , getSourceFileByPath: , …}
16 | sourceFile:SourceFileObject {pos: 0, end: 7, flags: 65536, …}
17 | span:Object {start: 0, length: 6}
18 | }
19 | ```
20 |
21 | You only really see `ChangeTrack` in use within the codefixes and refactors given that the other case where
22 | TypeScript emits files is a single operation of emission.
23 |
24 | The change tracker keeps track of individual changes to be applied to a file. There are [currently][1] four main
25 | APIs that it works with:
26 | `type Change = ReplaceWithSingleNode | ReplaceWithMultipleNodes | RemoveNode | ChangeText;`
27 |
28 | The `ChangeTrack` class is then used to provide high level API to describe the sort of changes you might want to
29 | make, which eventually fall into one of the four categories above.
30 |
31 | ### Making Changes
32 |
33 | The end result of using a `ChangeTrack` object is an array of `FileTextChanges` objects. The `ChangeTrack.with`
34 | function lets you work with a tracker instance elsewhere and passes back the `ChangeTrack` objects.
35 |
36 | The core work in generating changes occurs in:
37 |
38 | - [`getTextChangesFromChanges`][4]
39 | - [`computeNewText`][5]
40 | - [`getFormattedTextOfNode`][6]
41 |
42 | Going from an AST node to text is done by creating a [`printer`][7] in [`getNonformattedText`][8]. The printer
43 | returns an unformatted node, which is then ran through [a formatter][./formatting.md] and the raw string
44 | substitution is done in [`applyChanges`][9].
45 |
46 | Changes look like this:
47 |
48 | ```ts
49 | [{ fileName: "/b.js", textChanges: [{ span: { start: 0, length: 0 }, newText: "// @ts-ignore\n" }] }];
50 | ```
51 |
52 | ### Writing
53 |
54 | [`newFileChanges`][3] handles passing the set of
55 |
56 |
57 | [0]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/services/textChanges.ts#L303
58 | [0]:
59 | [1]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/services/textChanges.ts#L136
60 | [1]:
61 | [2]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/services/textChanges.ts#L1134
62 | [2]:
63 | [3]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/services/textChanges.ts#L1022
64 | [3]:
65 | [4]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/services/textChanges.ts#L994
66 | [4]:
67 | [5]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/services/textChanges.ts#L1035
68 | [5]:
69 | [6]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/services/textChanges.ts#L1065
70 | [6]:
71 | [7]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/compiler/emitter.ts#L852
72 | [7]:
73 | [8]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/services/textChanges.ts#L1088
74 | [8]:
75 | [8]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/services/textChanges.ts#L1101
76 | [8]:
77 |
78 |
--------------------------------------------------------------------------------
/debugging/README.md:
--------------------------------------------------------------------------------
1 | ## Debugging TypeScript
2 |
3 | * [[Performance]]
4 | * [[Performance-Tracing]]
5 |
6 | * [[Debugging-Language-Service-in-VS-Code]]
7 | * [[Getting-logs-from-TS-Server-in-VS-Code]]
8 | * [[JavaScript-Language-Service-in-Visual-Studio]]
9 | * [[Providing-Visual-Studio-Repro-Steps]]
10 |
--------------------------------------------------------------------------------
/dev-mode-screenshots/001.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/dev-mode-screenshots/001.png
--------------------------------------------------------------------------------
/dev-mode-screenshots/002.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/dev-mode-screenshots/002.png
--------------------------------------------------------------------------------
/dev-mode-screenshots/003.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/dev-mode-screenshots/003.png
--------------------------------------------------------------------------------
/dev-mode-screenshots/004.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/dev-mode-screenshots/004.png
--------------------------------------------------------------------------------
/dev-mode-screenshots/005.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/dev-mode-screenshots/005.png
--------------------------------------------------------------------------------
/dev-mode-screenshots/006.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/dev-mode-screenshots/006.png
--------------------------------------------------------------------------------
/images/addNewPackageSource.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/images/addNewPackageSource.PNG
--------------------------------------------------------------------------------
/images/architecture.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/images/architecture.png
--------------------------------------------------------------------------------
/images/array.map.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/images/array.map.png
--------------------------------------------------------------------------------
/images/decl1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/images/decl1.png
--------------------------------------------------------------------------------
/images/destructuring.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/images/destructuring.png
--------------------------------------------------------------------------------
/images/enable-salsa-dev15.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/images/enable-salsa-dev15.png
--------------------------------------------------------------------------------
/images/new-in-typescript/pretty01.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/images/new-in-typescript/pretty01.png
--------------------------------------------------------------------------------
/images/new-in-typescript/tsconfig-in-vs.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/images/new-in-typescript/tsconfig-in-vs.png
--------------------------------------------------------------------------------
/images/react.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/images/react.png
--------------------------------------------------------------------------------
/images/searchForMyGetPackage.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/images/searchForMyGetPackage.PNG
--------------------------------------------------------------------------------
/images/searchForNuGetPackage.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/images/searchForNuGetPackage.png
--------------------------------------------------------------------------------
/images/tracingCheckVariableDeclaration.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/images/tracingCheckVariableDeclaration.png
--------------------------------------------------------------------------------
/images/tracingExpanded.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/images/tracingExpanded.png
--------------------------------------------------------------------------------
/images/tracingJustOpened.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/images/tracingJustOpened.png
--------------------------------------------------------------------------------
/images/tracingTypes.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/TypeScript-wiki/756ece4f4b4c53758f93ade13cdd2d2457bd4c39/images/tracingTypes.png
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "dependencies": {
3 | "markdown-magic": "^1.0.0",
4 | "typescript": "latest",
5 | "glob": "^7.1.6",
6 | "escape-regex-string": "^1.0.6"
7 | },
8 | "scripts": {
9 | "build": "md-magic --path '**/*.md'",
10 | "lint": "node scripts/convertRelativeLinksToHardcoded.js **/*.md"
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/reference/Reference-Checker-Inference.md:
--------------------------------------------------------------------------------
1 |
2 | [0]: https://github.com/microsoft/TypeScript/blob/db9e0079/src/compiler/checker.ts#L21772
3 |
4 | # Type Inference
5 |
6 | TypeScript has a number of related techniques which together are
7 | called type inference: places where a type is discovered from
8 | inspecting values instead of a type annotation. This document
9 | covers them all in one place even though they're all fairly different.
10 |
11 | One thing that that is true of all type inference in TypeScript:
12 | type inference is a separate step that happens before checking. The
13 | checker will infer a type for a location; then it will check the type
14 | in the normal way, as if the type had been explicitly written. This
15 | results in redundant checking when the type inference is simple.
16 |
17 | None of these techniques are Hindley-Milner type inference. Instead,
18 | TypeScript adds a few ad-hoc inference techniques to its normal
19 | type-checking. The result is a system that can infer from many useful
20 | locations, but nowhere near all of them.
21 |
22 | ## Initialiser inference
23 |
24 | The simplest kind of inference is from initialisers. This inference is
25 | so simple that I don't believe it has been given a separate name until
26 | now.
27 |
28 | You can see this anywhere a variable, parameter or property has an
29 | initialiser:
30 |
31 | ```ts
32 | let x = 123
33 | function f(x = 123) {
34 | }
35 | class C {
36 | x = 123
37 | }
38 | ```
39 |
40 | Remember, inference precedes checking, so checking `let x = 123`
41 | looks like this:
42 |
43 | 1. Look for the type of `x`.
44 | 2. There is no annotation, so use the (widened) type of the initialiser: `number`.
45 | 3. Check that the initialiser's type `123` is assignable to `number`.
46 |
47 | ## Contextual typing
48 |
49 | Contextual typing looks upward in the tree for a type based on a type
50 | annotation. This is unlike initialiser inference, which looks at a *sibling*
51 | node for a type based on a *value*. For example, in
52 |
53 | ```ts
54 | const f: Callback = (a,b) => a.length + b
55 | ```
56 |
57 | The parameters `a` and `b` are contextually typed by the type
58 | `Callback`. The checker discovers this by looking at the parent nodes
59 | of `a` and `b` until it finds a type annotation on a variable declaration.
60 |
61 | In fact, contextual typing only applies to two kinds of things:
62 | parameters and literals (including JSX literals). But it may find a type in a variety of places.
63 | Here are 3 typical ones:
64 |
65 | 1. A type annotation on a declaration:
66 |
67 | ```ts
68 | type Config = { before(data: string): void }
69 | const cfg: Config = {
70 | before(x) {
71 | console.log(x.length)
72 | }
73 | }
74 | ```
75 |
76 | 2. The left-hand side of an assignment:
77 |
78 | ```ts
79 | let steps: ('up' | 'down' | 'left' | 'right')[] = ['up', 'up', 'down', 'down']
80 | steps = ['down']
81 | ```
82 |
83 | 3. An argument in a function call:
84 |
85 | ```ts
86 | declare function setup(register: (name: string, age: number) => void): void
87 | setup((name, age) => console.log(name, age))
88 | ```
89 |
90 | The basic mechanism of contextual typing is a search for a type
91 | annotation. Once a type annotation is found, contextual typing walks
92 | down through the *type* by reversing the path it walked up through the
93 | *tree*.
94 |
95 | Aside: In example (2), contextual typing gives `'down'` the
96 | *non-widening* type `'down'`; it would otherwise have the type
97 | `string`. That means `['down']` will have the type `'down'[]`, which
98 | is assignable to `steps`. So contextual typing lets programmers avoid
99 | writing `['down' as 'down']` in some cases.
100 |
101 | ### Walkthrough
102 |
103 | Let's walk through example (1).
104 |
105 | 1. During normal check of the tree,
106 | `checkFunctionExpressionOrObjectLiteralMethod` is called on
107 | `before`.
108 | 2. This calls `getApparentTypeofContextualType` (after a few
109 | intermediate functions), which
110 | recursively looks for the contextual type of `before`'s parent.
111 | 3. The parent is an object literal, which recursively looks for the
112 | contextual type of the object literal's parent.
113 | 4. The parent is a variable declaration with a type annotation `Config`.
114 | This is the contextual type of the object literal.
115 | 5. Next we look inside `Config` for a property named `before`. Since's
116 | `Config.before`'s type is a signature, that signature is the
117 | contextual type of `before`.
118 | 6. Finally, `assignContextualParameterTypes` assigns a type for `x` from
119 | `Config.before`'s first parameter.
120 |
121 | Note that if you have type annotations on some parameters already,
122 | `assignContextualParameterTypes` will skip those parameters.
123 |
124 | Contextually typing `(name, age) => ...` in (3) works substantially
125 | that same. When the search reaches `getContextualType`, instead of a
126 | variable declaration, the parent is a call expression. The contextual
127 | type of a call expression is the type of the callee, `setup` in this
128 | case. Now, as before, we look inside `setup`'s type: `(name, age) =>
129 | ...` is the first argument, so its contextual type is from the first
130 | parameter of `setup`, `register`. `assignmentContextualParameterTypes`
131 | works for `name` and `age` as in (1).
132 |
133 | ## Type Parameter Inference
134 |
135 | Type parameter inference is quite different from the other two
136 | techniques. It still infers **types** based on provided **values**,
137 | but the inferred types don't replace a type annotation. Instead
138 | they're provided as type arguments to a function, which results in
139 | instantiating a generic function with some specific type. For example:
140 |
141 | ```ts
142 | declare function setup(config: { initial(): T }): T
143 | setup({ initial() { return "last" } })
144 | ```
145 |
146 | First checks `{ initial() { return "last" } }` to get `{ initial():
147 | string }`. By matching `T` in `{ initial(): T }` with `string` in `{
148 | initial(): string }`, it infers that `T` is `string`, making the
149 | second line the same as if the author had written:
150 |
151 | ```ts
152 | setup({ initial() { return "last" } })
153 | ```
154 |
155 | Meaning that the compiler then checks that
156 | `{ initial() { return "last" } }` is assignable to
157 | `{ initial(): string }`.
158 |
159 | ### Walkthrough
160 |
161 | Type parameter inference starts off in `inferTypeArguments`, where
162 | the first step in type parameter inference is to get the type of all
163 | the arguments to the function whose parameters are being inferred. In
164 | the above example, the checker says that the type of
165 | `{ initial() { return "last" } }` is `{ initial(): string }`. This
166 | type is called the **source** type, since it is the source of
167 | inferences. It's matched with the parameter type `{ initial(): T }`.
168 | This is the **target** type -- it contains type parameters which are
169 | the target of the process.
170 |
171 | Type parameter inference is a pairwise walk of the two types, looking
172 | for type parameters in the target, matching them to corresponding
173 | types in the source. The type is walked structurally sort of like a tree
174 | is elsewhere in the compiler.
175 |
176 | 1. `inferTypes` gets called on each source/target pair with
177 | argument=source/parameter=target. There's only one pair here:
178 | `{ initial(): string }` and `{ initial(): T }`.
179 | 2. Since both sides are object types, `inferFromProperties` looks
180 | through each property of the target and looks for a match in the
181 | source. In this case both have the property `initial`.
182 | 3. `initial`'s type is a signature on both sides
183 | (`() => T/() => string`), so inference goes to `inferFromSignature`, which
184 | recursively infers from the return type.
185 | 4. Now the source/target pair is `T/string`. Since the source is a
186 | lone type parameter, we add `string` to the list of candidates for
187 | `T`.
188 |
189 | Once all the parameters have had `inferTypes` called on them,
190 | `getInferredTypes` condenses each candidate array to a single type,
191 | via `getUnionType` in this case. `T`'s candidates array is `[string]`,
192 | so `getUnionType` immediately returns `string`.
193 |
194 | ### Other considerations
195 |
196 | #### Method of Combining Candidate Arrays
197 |
198 | Only inference to return types, `keyof T` and mapped type constraints
199 | (which are usually `keyof` too) produce a union. These are all
200 | contravariant inference locations. All other locations
201 | call the custom code `getCommonSupertype`, which more or less does
202 | what it says. Note that object types are always unioned together
203 | first, regardless of inference position.
204 |
205 | #### Interference Between Contextual Typing and Type Parameter Inference
206 |
207 | Type parameter inference actually operates in two passes. The first
208 | pass skips arguments that have contextually typed expressions so that
209 | if good inferences are found from other arguments, contextual typing
210 | can provide types to parameters of function expressions, which in turn
211 | may produce better return types. Then the second pass proceeds with
212 | all arguments.
213 |
214 | #### Inference Priorities
215 |
216 | Different positions have different inference priorities; when the type
217 | walk finds a candidate at a higher priority position than existing
218 | candidates, it throws away the existing candidates and starts over
219 | with the higher-priority candidate. For example, a lone type variable
220 | has the highest priority, but a type variable found inside a return type
221 | has one of the lowest priorities.
222 |
223 | Priorities have two important limitations:
224 | first, they are defined ad-hoc, based on heuristics developed by
225 | observing bad type inferences and trying to fix them. Second, throwing away
226 | low-priority inferences is faster, but will miss some inferences
227 | compared to integrating all priorities in some way.
228 |
229 | #### Contravariant Candidates
230 |
231 | Certain candidates are inferred contravariantly, such as parameters of
232 | callbacks. This is a separate system from inference priorities;
233 | contravariant candidates are even higher priority.
234 |
235 | #### Reverse Mapped Types
236 |
237 | A reverse mapped type is a mapped type that is constructed during
238 | inference, and it requires information obtained from inference, but is
239 | not a central part of inference. A reverse mapped type is constructed when
240 | the target is a mapped type and the source is an object type. It
241 | allows a inference to apply to every member of an object type:
242 |
243 | ```ts
244 | type Box = { ref: T }
245 | type Boxed = { [K in keyof T]: Box }
246 | declare function unbox(boxed: Boxed): T;
247 | unbox({ a: { ref: 1 }, m: { ref: "1" } }) // returns { a: number, m: string }
248 | ```
249 |
250 | Reverse mapped types are normal types just like conditional types,
251 | index types, mapped types, etc. The difference is that they have no
252 | explicit syntax to construct them.
253 |
254 |
255 |
256 | [0]:
257 | [1]: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-6.html#strict-function-types
258 |
259 |
260 |
--------------------------------------------------------------------------------
/reference/Reference-Checker-Widening-Narrowing.md:
--------------------------------------------------------------------------------
1 | # Widening and Narrowing in Typescript
2 |
3 | Typescript has a number of related concepts in which a type gets
4 | treated temporarily as a similar type. Most of these concepts are
5 | internal-only. None of them are documented very well. For the internal
6 | concepts, we expect nobody needs to know about them to use the
7 | language. For the external concepts, we hope that they work well
8 | enough that most people *still* don't need to think about them. This
9 | document explains them all, aiming to help two audiences: (1) advanced
10 | users of Typescript who *do* need to understand the quirks of the
11 | language (2) contributors to the Typescript compiler.
12 |
13 | The concepts covered in this document are as follows:
14 |
15 | 1. Widening: treat an internal type as a normal one.
16 | 2. Literal widening: treat a literal type as a primitive one.
17 | 3. Narrowing: remove constituents from a union type.
18 | 4. Instanceof narrowing: treat a type as a subclass.
19 | 5. Apparent type: treat a non-object type as an object type.
20 |
21 | ## Widening
22 |
23 | Widening is the simplest operation of the bunch. The types `null` and
24 | `undefined` are converted to `any`. This happens
25 | recursively in object types, union types, and array types (including
26 | tuples).
27 |
28 | Why widening? Well, historically, `null` and `undefined` were internal
29 | types that needed to be converted to `any` for downstream consumers
30 | and for display. With `--strictNullChecks`, widening doesn't happen
31 | any more. But without it, widening happens a lot, generally when obtaining
32 | a type from another object. Here are some examples:
33 |
34 | ```ts
35 | // @strict: false
36 | let x = null;
37 | ```
38 |
39 | Here, `null` has the type `null`, but `x` has the type `any` because
40 | of widening on assignment. `undefined` works the same way. However,
41 | with `--strict`, `null` is preserved, so no widening will happen.
42 |
43 | ## Literal widening
44 |
45 | Literal widening is significantly more complex than "classic"
46 | widening. Basically, when literal widening happens, a literal type
47 | like `"foo"` or `SomeEnum.Member` gets treated as its base type:
48 | `string` or `SomeEnum`, respectively. The places where literals widen,
49 | however, cause the behaviour to be hard to understand. Literal
50 | widening is described fully
51 | [at the literal widening PR](https://github.com/Microsoft/TypeScript/pull/10676)
52 | and
53 | [its followup](https://github.com/Microsoft/TypeScript/pull/11126).
54 |
55 | ### When does literal widening happen?
56 |
57 | There are two key points to understand about literal widening.
58 |
59 | 1. Literal widening only happens to literal types that originate from
60 | expressions. These are called *fresh* literal types.
61 | 2. Literal widening happens whenever a fresh literal type reaches a
62 | "mutable" location.
63 |
64 | For example,
65 |
66 | ```ts
67 | const one = 1; // 'one' has type: 1
68 | let num = 1; // 'num' has type: number
69 | ```
70 |
71 | Let's break the first line down:
72 |
73 | 1. `1` has the fresh literal type `1`.
74 | 2. `1` is assigned to `const one`, so `one: 1`. But the type `1` is still
75 | fresh! Remember that for later.
76 |
77 | Meanwhile, on the second line:
78 |
79 | 1. `1` has the fresh literal type `1`.
80 | 2. `1` is assigned to `let num`, a mutable location, so `num: number`.
81 |
82 | Here's where it gets confusing. Look at this:
83 |
84 | ```ts
85 | const one = 1;
86 | let wat = one; // 'wat' has type: number
87 | ```
88 |
89 | The first two steps are the same as the first example. The third step
90 |
91 | 1. `1` has the fresh literal type `1`.
92 | 2. `1` is assigned to `const one`, so `one: 1`.
93 | 3. `one` is assigned to `wat`, a mutable location, so `wat: number`.
94 |
95 | This is pretty confusing! The fresh literal type `1` makes its way
96 | *through* the assignment to `one` down to the assignment to `wat`. But
97 | if you think about it, this is what you want in a real program:
98 |
99 | ```ts
100 | const start = 1001;
101 | const max = 100000;
102 | // many (thousands?) of lines later ...
103 | for (let i = start; i < max; i = i + 1) {
104 | // did I just write a for loop?
105 | // is this a C program?
106 | }
107 | ```
108 |
109 | If the type of `i` were `1001` then you couldn't write a for loop based
110 | on constants.
111 |
112 | There are other places that widen besides assignment. Basically it's
113 | anywhere that mutation could happen:
114 |
115 | ```ts
116 | const nums = [1, 2, 3]; // 'nums' has type: number[]
117 | nums[0] = 101; // because Javascript arrays are always mutable
118 |
119 | const doom = { e: 1, m: 1 }
120 | doom.e = 2 // Mutable objects! We're doomed!
121 |
122 | // Dooomed!
123 | // Doomed!
124 | // -gasp- Dooooooooooooooooooooooooooooooooo-
125 | ```
126 |
127 | ### What literal types widen?
128 |
129 | * Number literal types like `1` widen to `number`.
130 | * String literal types like `'hi'` widen to `string`.
131 | * Boolean literal types like `true` widen to `boolean`.
132 | * Enum members widen to their containing enum.
133 |
134 | An example of the last is:
135 |
136 | ```ts
137 | enum State {
138 | Start,
139 | Expression,
140 | Term,
141 | End
142 | }
143 | const start = State.Start;
144 | let state = start;
145 | let ch = '';
146 | while (ch = nextChar()) {
147 | switch (state) {
148 | // ... imagine your favourite tokeniser here
149 | }
150 | }
151 | ```
152 |
153 | ## Narrowing
154 |
155 | Narrowing is essentially the removal of types from a union. It's
156 | happening all the time as you write code, especially if you use
157 | `--strictNullChecks`. To understand narrowing, you first need to
158 | understand the difference between "declared type" and "computed type".
159 |
160 | The declared type of a variable is the one it's declared with. For
161 | `let x: number | undefined`, that's `number | undefined`. The computed
162 | type of a variable is the type of the variable as it's used in
163 | context. Here's an example:
164 |
165 | ```ts
166 | // @strict: true
167 | type Thing = { name: 'one' | 'two' };
168 | function process(origin: Thing, extra?: Thing | undefined): void {
169 | preprocess(origin, extra);
170 | if (extra) {
171 | console.log(extra.name);
172 | if (extra.name === 'one') {
173 | // ...
174 | ```
175 |
176 | `extra`'s declared type is `Thing | undefined`, since it's an optional
177 | parameter. However, its computed type varies based on context. On the
178 | first line, in `preprocess(origin, extra)`, its computed type is still
179 | `Thing | undefined`. However, inside the `if (extra)` block, `extra`'s
180 | computed type is now just `Thing` because it can't possibly be
181 | `undefined` due to the `if (extra)` check. Narrowing has removed
182 | `undefined` from its type.
183 |
184 | Similarly, the declared type of `extra.name` is `'one' | 'two'`, but
185 | inside the true branch of `if (extra.name === 'one')`, its computed
186 | type is just `'one'`.
187 |
188 | Narrowing mostly commonly removes all but one type from a union, but
189 | doesn't necessarily need to:
190 |
191 | ```ts
192 | type Type = Anonymous | Class | Interface
193 | function f(thing: string | number | boolean | object) {
194 | if (typeof thing === 'string' || typeof thing === 'number') {
195 | return lookup[thing];
196 | }
197 | else if (typeof thing === 'boolean' && thing) {
198 | return globalCachedThing;
199 | }
200 | else {
201 | return thing;
202 | }
203 | }
204 | ```
205 |
206 | Here, in the first if-block, `thing` narrows to `string | number` because
207 | the check allows it to be either string or number.
208 |
209 | ## Instanceof Narrowing
210 |
211 | Instanceof narrowing looks similar to normal narrowing, and
212 | behaves similarly, but its rules are somewhat different. It only
213 | applies to certain `instanceof` checks and type predicates.
214 |
215 | Here's a use of `instanceof` that follows the normal narrowing rules:
216 |
217 | ```ts
218 | class C { c: any }
219 | function f(x: C | string) {
220 | if (x instanceof C) {
221 | // x is C here
222 | }
223 | else {
224 | // x is string here
225 | }
226 | }
227 | ```
228 |
229 | So far this follows the normal narrowing rules. But `instanceof`
230 | applies to subclasses too:
231 |
232 | ```ts
233 | class D extends C { d: any }
234 | function f(x: C) {
235 | if (x instanceof D) {
236 | // x is D here
237 | }
238 | else {
239 | // x is still just C here
240 | }
241 | }
242 | ```
243 |
244 | Unlike narrowing, `instanceof` narrowing doesn't remove any types to
245 | get `x`'s computed type. It just notices that `D` is a subclass of `C`
246 | and changes the computed type to `D` inside the `if (x instanceof D)`
247 | block. In the `else` block `x` is still `C`.
248 |
249 | If you mess up the class relationship, the compiler does its best
250 | to make sense of things:
251 |
252 | ```ts
253 | class E { e: any } // doesn't extend C!
254 | function f(x: C) {
255 | if (x instanceof E) {
256 | // x is C & E here
257 | }
258 | else {
259 | // x is still just C here
260 | }
261 | }
262 | ```
263 |
264 | The compiler thinks that something of type `C` can't also be
265 | `instanceof E`, but just in case, it sets the computed type of `x` to
266 | `C & E`, so that you can use the properties of `E` in the block
267 | — just be aware that the block will probably never execute!
268 |
269 | ### Type predicates
270 |
271 | Type predicates follow the same rules as `instanceof` when narrowing,
272 | and are just as subject to misuse. So this example is equivalent to
273 | the previous wonky one:
274 |
275 | ```ts
276 | function isE(e: any): e is E {
277 | return e.e;
278 | }
279 | function f(x: C) {
280 | if (isE(x)) {
281 | // x is C & E here
282 | }
283 | else {
284 | // nope, still just C
285 | }
286 | }
287 | ```
288 |
289 | ## Apparent Type
290 |
291 | In some situations you need to get the properties on a variable, even
292 | when it technically doesn't have properties. One example is primitives:
293 |
294 | ```ts
295 | let n = 12
296 | let s = n.toFixed()
297 | ```
298 |
299 | `12` doesn't technically have properties; `Number` does. In order to
300 | map `number` to `Number`, we define `Number` as the *apparent type* of
301 | `number`. Whenever the compiler needs to get properties of some type,
302 | it asks for the apparent type of that type first. This applies to
303 | other non-object types like type parameters:
304 |
305 | ```ts
306 | interface Node {
307 | parent: Node;
308 | pos: number;
309 | kind: number;
310 | }
311 | function setParent(node: T, parent: Node): T {
312 | node.parent = parent;
313 | return node;
314 | }
315 | ```
316 |
317 | `T` is a type parameter, which is just a placeholder. But its
318 | constraint is `Node`, so when the compiler checks `node.parent`, it
319 | gets the apparent type of `T`, which is `Node`. Then it sees that
320 | `Node` has a `parent` property.
321 |
--------------------------------------------------------------------------------
/reference/test.md:
--------------------------------------------------------------------------------
1 | Can anyone see this?
2 |
--------------------------------------------------------------------------------
/scripts/convertRelativeLinksToHardcoded.js:
--------------------------------------------------------------------------------
1 | // @ts-check
2 |
3 | // Loop through all files switching a reference like:
4 | // [13]:
5 | // to
6 | // [13]: https://github.com/microsoft/TypeScript/blob/8d986554/src/compiler/checker.ts#L30308
7 | //
8 |
9 | // Validate:
10 | // node scripts/convertRelativeLinksToHardcoded.js scripts/fixtures/input.md
11 |
12 | // Write:
13 | // node scripts/convertRelativeLinksToHardcoded.js scripts/fixtures/input.md --write
14 |
15 | const glob = require("glob");
16 | const { readFileSync, writeFileSync, existsSync } = require("fs");
17 | const { join } = require("path");
18 | const { execSync } = require("child_process");
19 | const escapeRegex = require("escape-regex-string");
20 |
21 | if (!process.argv[2]) throw new Error("Did not include a glob for markdown files to change");
22 |
23 | // This can be anything
24 | const write = process.argv[3] !== undefined;
25 |
26 | const possibleTSRepo = ["../typescript-compiler", "../TypeScript", "TypeScript"];
27 | let repoPath = possibleTSRepo.find(f => existsSync(join(f, "package.json")));
28 | if (!repoPath) throw new Error("Could not find a TypeScript repo");
29 |
30 | const repoHead = execSync(`git rev-parse HEAD | cut -c 1-8`, { cwd: repoPath, encoding: "utf8" });
31 | if (!repoHead) throw new Error("Could not get the git info from the sibling TypeScript repo");
32 |
33 | const files = glob.sync(process.argv[2]);
34 | if (!files.length) throw new Error("Did not get any files with that glob");
35 |
36 | let failed = [];
37 |
38 | files.forEach(file => {
39 | if (file === "README.md") return;
40 |
41 | let content = readFileSync(file, "utf8");
42 | // https://regex101.com/r/w1dEG1/1
43 | const regex = new RegExp(/\[.*]: <(.*) - (.*)>/g);
44 |
45 | let result;
46 | while ((result = regex.exec(content))) {
47 | const fileRef = result[1];
48 | const searchTerm = result[2];
49 | const original = `: <${fileRef} - ${searchTerm}>`;
50 | try {
51 | const originalFile = readFileSync(join(repoPath, fileRef), "utf8");
52 | const line = getLineNo(originalFile, new RegExp(escapeRegex(searchTerm)));
53 | const lineRef = line && line[0] && line[0].number ? `#L${line[0].number}` : "";
54 | const replacement = `: https://github.com/microsoft/TypeScript/blob/${repoHead.trim()}/${fileRef}${lineRef}`;
55 | content = content.replace(original, replacement);
56 | } catch (e) {
57 | failed.push([file, fileRef]);
58 | }
59 | }
60 |
61 | if (write) {
62 | writeFileSync(file, content);
63 | } else {
64 | console.log(content);
65 | }
66 | });
67 |
68 | if (failed.length) {
69 | console.error("Could not find the following references to update:");
70 | console.error(failed);
71 |
72 | console.error("Either ping @orta if confused about this failure, or update the filepaths please. It's likely they've moved in the TypeScript repo.");
73 | process.exit(1);
74 | }
75 |
76 | /*!
77 | * line-number
78 | *
79 | * Copyright (c) 2014 Jon Schlinkert, contributors.
80 | * Licensed under the MIT License
81 | */
82 | function getLineNo(str, re) {
83 | return str
84 | .split(/\r?\n/)
85 | .map(function(line, i) {
86 | if (re.test(line)) {
87 | return {
88 | line: line,
89 | number: i + 1,
90 | match: line.match(re)[0]
91 | };
92 | }
93 | })
94 | .filter(Boolean);
95 | }
96 |
--------------------------------------------------------------------------------
/scripts/fixtures/input.md:
--------------------------------------------------------------------------------
1 | # Checker
2 |
3 | Ok, yeah, so it's a 30k LOC file. Why 30k lines in one file? Well there's a few main arguments:
4 |
5 | - All of the checker is in one place.
6 | - Save memory by making it a global, to quote a comment in the parser:
7 |
8 | > ```
9 | > // Implement the parser as a singleton module. We do this for perf reasons because creating parser instances
10 | > // can actually be expensive enough to impact us on projects with many source files.
11 | > ```
12 |
13 | * Lots of these functions need to know a lot about each other, the top of the function `createTypeChecker` has a
14 | set of variables which are global within all of these functions and are liberally accessed.
15 |
16 | Switching to different files means probably making [god objects][god], and the checker needs to be extremely
17 | fast. We want to avoid additional calls for ambient context. There are architectural patterns for this, but it's
18 | better to assume good faith that they've been explored already (8 years down the line now.)
19 |
20 | Anyway, better to get started somewhere. I [asked online](https://twitter.com/orta/status/1148335807780007939)
21 | about how people would try to study a file like this and I think one of the best paths is by following a
22 | particular story as a file gets checked.
23 |
24 | ## An entry-point
25 |
26 | The likely entry point is via a Program. The program has a memoized typechecker created in
27 | [`getDiagnosticsProducingTypeChecker`][0] which creates a type checker.
28 |
29 | The initial start of type checking starts with [`getDiagnosticsWorker`][1], worker in this case isn't a threading
30 | term I believe ( at least I can't find anything like that in the code ) - it is set up to listen for diagnostic
31 | results (e.g. warns/fails) and then triggers [`checkSourceFileWorker`][2].
32 |
33 | This function starts at the root `Node` of any TS/JS file node tree: `SourceFile`. It will then have to recurse
34 | through all of the [AST][ast] nodes in it's tree.
35 |
36 | It doesn't start with a single recursive function though, it starts by looking through the SourceFile's
37 | [`statements`][4] and through each one of those to get all the nodes. For example:
38 |
39 | ```ts
40 | // Statement 1
41 | const hi = () => "Hello";
42 |
43 | // Statement 2
44 | console.log(hi());
45 | ```
46 |
47 | Which looks a bit like:
48 |
49 | ```sh
50 | SourceFile
51 | statements:
52 |
53 | - VariableStatement
54 | - declarationList: VariableDeclarationList # (because any const cna have many declarations in a row... )
55 | - variables: VariableStatement
56 | - etc
57 |
58 | - ExpressionStatement
59 | - expression: CallExpression # outer console.log
60 | - expression: PropertyAccessExpression
61 | - etc
62 | - arguments: CallExpression
63 | - etc
64 | ```
65 |
66 | [See AST Explorer](https://astexplorer.net/#/gist/80c981c87035a45a753c0ee5c983ecc9/6276351b153f4dac9811bf7214c9b236ae420c7e)
67 |
68 | Each node has a different variable to work with (so you can't just say
69 | `if node.children { node.children.foreach(lookAtNode) }` ) but instead you need to examine each node individually.
70 |
71 | ## Checking a Statement
72 |
73 | Initially the meat of the work starts in [`checkSourceElementWorker`][6] which has a by `switch` statement that
74 | contains all legitimate nodes which can start a statement. Each node in the tree then does it's checking.
75 |
76 | Let's try get a really early error, with this bad code:
77 |
78 | ```ts
79 | // A return statement shouldn't exist here in strict mode (or any mode?)
80 | return;
81 | ~~~~~~
82 | ```
83 |
84 | It goes into [`checkReturnStatement`][6] which uses [`getContainingFunction`][7] to determine if the `return`
85 | lives inside a [`function-like`][8] node ( e.g. `MethodSignature`, `CallSignature`, `JSDocSignature`,
86 | `ConstructSignature`, `IndexSignature`, `FunctionType`, `JSDocFunctionType`, `ConstructorType`).
87 |
88 | Because the parent of the `return` statement is the root (`parent: SourceFileObject`) then it's going to fail.
89 | This triggers [`grammarErrorOnFirstToken`][9] which will raise the error:
90 | `A 'return' statement can only be used within a function body.ts(1108)` and declare the error underline to the
91 | first token inside that node.
92 |
93 | ## Checking Type Equality
94 |
95 | ```ts
96 | const myString = "Hello World";
97 | const myInt = 123;
98 | // Error: This condition will always return 'false' since the types '123' and '"Hello World"' have no overlap.
99 | if (myInt === myString) {
100 | // Do something
101 | }
102 | ```
103 |
104 | To get to this error message:
105 |
106 | - [`checkSourceElementWorker`][6] loops through the 3 statements in the `SourceFile`
107 | - In the third, it goes through:
108 | - [`checkIfStatement`][13]
109 | - [`checkTruthinessExpression`][11]
110 | - [`checkExpression`][12]
111 | - [`checkBinaryLikeExpression`][14] where it fails.
112 | - The fail comes from inside [`isTypeRelatedTo`][15] which has a set of heuristics for whether the types are the
113 | same ([`isSimpleTypeRelatedTo`][16] uses cached data in NodeLinks, and [`checkTypeRelatedTo`][17] dives deeper)
114 | and if not then. It will raise.
115 |
116 | ### Caching Data While Checking
117 |
118 | Note there are two ways in which TypeScript is used, as a server and as a one-off compiler. In a server, we want
119 | to re-use as much as possible between API requests, and so the Node tree is treated as immutable data until there
120 | is a new AST.
121 |
122 | This gets tricky inside the Type Checker, which for speed reasons needs to cache data somewhere. The solution to
123 | this is the [`NodeLinks`][3] property on a Node. The Type Checker fills this up during the run and re-uses it,
124 | then it is discarded next time you re-run the checker.
125 |
126 | ### Type Flags
127 |
128 | Because TypeScript is a [structural type system][20], every type can reasonably be compared with every other type.
129 | One of the main ways in which TypeScript keeps track of the underlying data-model is via the
130 | [`enum TypeFlags`][19]. Accessed via `.flags` on any node, it is a value which is used via bitmasking to let you
131 | know what data it represents.
132 |
133 | If you wanted to check for whether the type is a union:
134 |
135 | ```ts
136 | if (target.flags & TypeFlags.Union && source.flags & TypeFlags.Object) {
137 | // is a union object
138 | }
139 | ```
140 |
141 | When running the compiler in debug mode, you can see a string version of this via `target.__debugFlags`.
142 |
143 | ### Type Comparison
144 |
145 | The entry point for comparing two types happens in [`checkTypeRelatedTo`][17]. This function is mostly about
146 | handling the diagnostic results from any checking though and doesn't do the work. The honour of that goes to
147 | [`isRelatedTo`][18] which:
148 |
149 | - Figures out what the source and target types should be (based on freshness (a literal which was created in an
150 | expression), whether it is substituted () or simplifiable (a type which depends first on resolving another
151 | type))
152 |
153 | - First, check if they're identical via [`isIdenticalTo`][21]. The check for most objects occurs in
154 | [`recursiveTypeRelatedTo`][22], unions and intersections have a check that compares each value in
155 | [`eachTypeRelatedToSomeType`][23] which eventually calls [`recursiveTypeRelatedTo`][22] for each item in the
156 | type.
157 |
158 | - The heavy lifting of the comparison depending on what flags are set on the node is done in
159 | [`structuredTypeRelatedTo`][23]. Where it picks off one by one different possible combinations for matching and
160 | returns early as soon as possible.
161 |
162 | A lot of the functions related to type checking return a [`Ternary`][24], which an enum with three states, true,
163 | false and maybe. This gives the checker the chance to admit that it probably can't figure out whether a match is
164 | true currently (maybe it hit the 100 depth limit for example) and potentially could be figured out coming in from
165 | a different resolution.
166 |
167 | TODO: what are substituted types?
168 |
169 | ## Debugging Advice
170 |
171 | - If you want to find a diagnostic in the codebase, search for `diag(WXZY` e.g ``, you'll find
172 | `src/compiler/diagnosticInformationMap.generated.ts` has it being referenced by a key. Search for that key.
173 |
174 | - If you're working from an error and want to see the path it took to get there, you can add a breakpoint in
175 | [`createFileDiagnostic`][10] which should get called for all diagnostic errors.
176 |
177 |
178 | [0]: https://github.com/microsoft/TypeScript/blob/1bb6ea03/src/compiler/program.ts#L1557
179 | [1]: https://github.com/microsoft/TypeScript/blob/1bb6ea03/src/compiler/checker.ts#L33799
180 | [2]: https://github.com/microsoft/TypeScript/blob/1bb6ea03/src/compiler/checker.ts#L33725
181 | [3]: https://github.com/microsoft/TypeScript/blob/1bb6ea03//src/compiler/types.ts#L4224
182 | [4]: GLOSSARY.md#statements
183 | [ast]: GLOSSARY.md#statements
184 | [5]: https://github.com/microsoft/TypeScript/blob/1bb6ea03/src/compiler/checker.ts#L33403
185 | [6]: https://github.com/microsoft/TypeScript/blob/1bb6ea03/src/compiler/checker.ts#L31745
186 | [7]: https://github.com/microsoft/TypeScript/blob/1bb6ea03/src/compiler/checker.ts
187 | [8]: https://github.com/microsoft/TypeScript/blob/1bb6ea03/src/compiler/utilities.ts
188 | [9]: https://github.com/microsoft/TypeScript/blob/1bb6ea03/src/compiler/checker.ts#L36624
189 | [10]: https://github.com/microsoft/TypeScript/blob/1bb6ea03/src/compiler/utilities.ts#L5083
190 | [11]:
191 | [12]:
192 | [13]: https://github.com/microsoft/TypeScript/blob/1bb6ea03/src/compiler/checker.ts#L30811
193 | [14]: https://github.com/microsoft/TypeScript/blob/1bb6ea03/src/compiler/checker.ts#L27263
194 | [15]: https://github.com/microsoft/TypeScript/blob/1bb6ea03/src/compiler/checker.ts#L14557
195 | [16]: https://github.com/microsoft/TypeScript/blob/1bb6ea03/src/compiler/checker.ts#L14520
196 | [17]: https://github.com/microsoft/TypeScript/blob/1bb6ea03/src/compiler/checker.ts#L13815
197 | [17]: https://github.com/microsoft/TypeScript/blob/1bb6ea03/src/compiler/checker.ts#L14898
198 | [19]: https://github.com/microsoft/TypeScript/blob/1bb6ea03/src/compiler/types.ts#L4251
199 | [20]: GLOSSARY.md#structural-type-system
200 | [21]: https://github.com/microsoft/TypeScript/blob/1bb6ea03/src/compiler/checker.ts#L15074
201 | [22]: https://github.com/microsoft/TypeScript/blob/1bb6ea03/src/compiler/checker.ts#L15313
202 | [22]: https://github.com/microsoft/TypeScript/blob/1bb6ea03/src/compiler/checker.ts#L15179
203 | [23]: https://github.com/microsoft/TypeScript/blob/1bb6ea03/src/compiler/checker.ts#L15397
204 |
205 |
--------------------------------------------------------------------------------
/tsconfig.json.md:
--------------------------------------------------------------------------------
1 | > ### This page has moved to http://www.typescriptlang.org/docs/handbook/tsconfig-json.html
2 |
--------------------------------------------------------------------------------