diff --git a/dangerfile.ts b/dangerfile.ts deleted file mode 100644 index a7bb8e284470..000000000000 --- a/dangerfile.ts +++ /dev/null @@ -1,43 +0,0 @@ -// This Dangerfile only runs on same-repo PRs - -// You can test it by running -// yarn danger pr https://github.com/microsoft/TypeScript-Website/pull/115 - -import { danger, message, markdown } from 'danger' -import {basename} from "path" -import spellcheck from 'danger-plugin-spellcheck' -import lighthouse from 'danger-plugin-lighthouse' - -// Spell check all the things -spellcheck({ - settings: 'artsy/peril-settings@spellcheck.json', - codeSpellCheck: ['Examples/**/*.ts', 'Examples/**/*.js'], -}) - -// Print out the PR url -const deployURL = `https://typescript-v2-${danger.github.pr.number}.ortam.now.sh` -message(`Deployed to [a PR branch](${deployURL}) - [tsconfig](${deployURL}/tsconfig) [old handbook](${deployURL}/docs/handbook/integrating-with-build-tools.html)`) - -// Look for new snapshots and show in a HTML table -const snapshots = danger.git.fileMatch("packages/typescriptlang-org/_tests/backstop_data/bitmaps_reference/*.png") -if (snapshots.modified) { - const oldSha = danger.github.pr.base.sha - const newSha = danger.github.pr.head.sha - - const tables = snapshots.getKeyedPaths().modified.map(p => { - const oldURL = `https://raw.githubusercontent.com/microsoft/TypeScript-Website/${oldSha}/${p}` - const newURL = `https://raw.githubusercontent.com/microsoft/TypeScript-Website/${newSha}/${p}` - - return ` -###### \`${basename(p)}\` - -Before | After -:-------------------------:|:-------------------------: -![](${oldURL}) | ![](${newURL}) -` - }) - - markdown(`## Snapshots updated\n\n ${tables.join("\n\n")}`) -} - -lighthouse() diff --git a/packages/gatsby-remark-twoslasher-code-blocks/index.js b/packages/gatsby-remark-twoslasher-code-blocks/index.js index 69174e336cfa..943c24c78232 100644 --- a/packages/gatsby-remark-twoslasher-code-blocks/index.js +++ b/packages/gatsby-remark-twoslasher-code-blocks/index.js @@ -1,4 +1,4 @@ -// @ts-enable +// // @ts-check const visit = require('unist-util-visit'); const {twoslasher} = require(require.resolve("ts-twoslasher")) diff --git a/packages/gatsby-remark-twoslasher-code-blocks/scripts/test.js b/packages/gatsby-remark-twoslasher-code-blocks/scripts/test.js index a6de01428ff3..41672472adf0 100644 --- a/packages/gatsby-remark-twoslasher-code-blocks/scripts/test.js +++ b/packages/gatsby-remark-twoslasher-code-blocks/scripts/test.js @@ -1,7 +1,7 @@ var remark = require("remark") var visit = require("unist-util-visit") -const { readFileSync }= require("fs") +const { readFileSync } = require("fs") var remark = require("remark") var visit = require("unist-util-visit") diff --git a/packages/sandbox/src/startPlayground.ts b/packages/sandbox/src/startPlayground.ts index 3d59d1cfa21a..3f9ffbc1eb54 100644 --- a/packages/sandbox/src/startPlayground.ts +++ b/packages/sandbox/src/startPlayground.ts @@ -23,7 +23,7 @@ type PlaygroundConfig = { const languageType = (config: PlaygroundConfig) => config.useJavaScript ? "javascript" : "typescript" const monacoLanguageDefaults = (config: PlaygroundConfig) => config.useJavaScript ? monaco.languages.typescript.javascriptDefaults : monaco.languages.typescript.typescriptDefaults -const monacoLanguageWorker = (config: PlaygroundConfig) => config.useJavaScript ? monaco.languages.typescript.getJavaScriptWorker : monaco.languages.typescript.getTypeScriptWorker +// const monacoLanguageWorker = (config: PlaygroundConfig) => config.useJavaScript ? monaco.languages.typescript.getJavaScriptWorker : monaco.languages.typescript.getTypeScriptWorker /** Default Monaco settings for playground */ diff --git a/packages/ts-twoslasher/test/README.md b/packages/ts-twoslasher/test/README.md new file mode 100644 index 000000000000..c4aa5df78e09 --- /dev/null +++ b/packages/ts-twoslasher/test/README.md @@ -0,0 +1,10 @@ +### Testing + +There are two types of tests: + +- Units which are Jest tests, and not unique to this project + +- Integration tests where you place a fixture code sample in the right folder and get a response JSON result. There are three folders for tests: + - `test/fixtures` - Any test in this file is shown in the README, so they should showcase features - not bugs + - `tests/fixtures/throws` - A test which should correctly raise + - `tests/fixtures/tests` - All other tests, repros etc diff --git a/packages/ts-twoslasher/test/fixtures.test.ts b/packages/ts-twoslasher/test/fixtures.test.ts index 66a4e67c372f..c2e7638ce1f7 100644 --- a/packages/ts-twoslasher/test/fixtures.test.ts +++ b/packages/ts-twoslasher/test/fixtures.test.ts @@ -52,6 +52,25 @@ describe('with fixtures', () => { }) }) + readdirSync(join(fixturesFolder, 'tests')).forEach(fixtureName => { + const fixture = join(fixturesFolder, 'tests', fixtureName) + if (lstatSync(fixture).isDirectory()) { + return + } + + // if(!fixtureName.includes("compiler_fl")) return + it('Hidden Fixtures: ' + fixtureName, () => { + const resultName = parse(fixtureName).name + '.json' + const result = join(resultsFolder, 'tests', resultName) + + const file = readFileSync(fixture, 'utf8') + + const fourslashed = twoslasher(file, extname(fixtureName).substr(1)) + const jsonString = format(JSON.stringify(fourslashed), { parser: 'json' }) + expect(jsonString).toMatchFile(result) + }) + }) + const throwingFixturesFolder = join(__dirname, 'fixtures', 'throws') readdirSync(throwingFixturesFolder).forEach(fixtureName => { diff --git a/packages/ts-twoslasher/test/fixtures/compiler_errors.ts b/packages/ts-twoslasher/test/fixtures/compiler_errors.ts index 03817449390f..4353a2d7ce43 100644 --- a/packages/ts-twoslasher/test/fixtures/compiler_errors.ts +++ b/packages/ts-twoslasher/test/fixtures/compiler_errors.ts @@ -5,4 +5,4 @@ function fn(s) { console.log(s.subtr(3)) } -fn(42); +fn(42) diff --git a/packages/ts-twoslasher/test/fixtures/tests/cut_files.ts b/packages/ts-twoslasher/test/fixtures/tests/cut_files.ts index db20a2798497..dcd4b061f3a5 100644 --- a/packages/ts-twoslasher/test/fixtures/tests/cut_files.ts +++ b/packages/ts-twoslasher/test/fixtures/tests/cut_files.ts @@ -1,4 +1,4 @@ // Hello should not appear in the staticQuickInfos -const hello = "world" +const hello = 'world' // ---cut--- -const bye = "globe" +const bye = 'globe' diff --git a/packages/ts-twoslasher/test/fixtures/tests/hidden_emit.ts b/packages/ts-twoslasher/test/fixtures/tests/hidden_emit.ts new file mode 100644 index 000000000000..fc83c649b2dc --- /dev/null +++ b/packages/ts-twoslasher/test/fixtures/tests/hidden_emit.ts @@ -0,0 +1,4 @@ +// @showEmit +// @removeComments: true +/** The translation of 'Hello world' into Portuguese */ +export declare const helloWorldPTBR = 'Olá Mundo' diff --git a/packages/ts-twoslasher/test/results/tests/hidden_emit.json b/packages/ts-twoslasher/test/results/tests/hidden_emit.json new file mode 100644 index 000000000000..4b8b5831529b --- /dev/null +++ b/packages/ts-twoslasher/test/results/tests/hidden_emit.json @@ -0,0 +1,9 @@ +{ + "code": "", + "extension": "js", + "highlights": [], + "queries": [], + "staticQuickInfos": [], + "errors": [], + "playgroundURL": "https://www.typescriptlang.org/play/#code/Q" +} diff --git a/packages/tsconfig-reference/README.md b/packages/tsconfig-reference/README.md index c1eb973407cd..e64d6c04c200 100644 --- a/packages/tsconfig-reference/README.md +++ b/packages/tsconfig-reference/README.md @@ -36,3 +36,17 @@ yarn workspace tsconfig-reference run generate-json yarn workspace tsconfig-reference run generate-markdown ``` + +You can validate any codeblocks which use twoslasher via the script: + +```sh +yarn workspace tsconfig-reference run test + +# or to just run the linter without a build +yarn workspace tsconfig-reference run lint + +# or to just one one linter +yarn workspace tsconfig-reference run lint resolveJson +``` + +You can debug twoslash by setting the environment var `DEBUG="*"` in all of these too. diff --git a/packages/tsconfig-reference/copy/en/categories/Advanced_Options_6178.md b/packages/tsconfig-reference/copy/en/categories/Advanced_Options_6178.md index 8943f230ca2e..e4a5539b8845 100644 --- a/packages/tsconfig-reference/copy/en/categories/Advanced_Options_6178.md +++ b/packages/tsconfig-reference/copy/en/categories/Advanced_Options_6178.md @@ -2,4 +2,4 @@ display: "Advanced" --- -Additional Checks Copy +Flags which help with debugging diff --git a/packages/tsconfig-reference/copy/en/categories/Basic_Options_6172.md b/packages/tsconfig-reference/copy/en/categories/Basic_Options_6172.md index 0b3c2d13bab8..4e513a558d42 100644 --- a/packages/tsconfig-reference/copy/en/categories/Basic_Options_6172.md +++ b/packages/tsconfig-reference/copy/en/categories/Basic_Options_6172.md @@ -1,5 +1,5 @@ --- -display: "Basic Options" +display: "Project Options" --- -Additional Checks Copy +These settings are used to define the runtime expectations of your project, how and where you want the JavaScript to be emitted and the level of integration you want with existing JavaScript code. diff --git a/packages/tsconfig-reference/copy/en/categories/Command_line_Options_6171.md b/packages/tsconfig-reference/copy/en/categories/Command_line_Options_6171.md index 4246dc0c8c6f..1de7ca5a0fd3 100644 --- a/packages/tsconfig-reference/copy/en/categories/Command_line_Options_6171.md +++ b/packages/tsconfig-reference/copy/en/categories/Command_line_Options_6171.md @@ -1,5 +1,3 @@ --- display: "Command Line" --- - -Additional Checks Copy diff --git a/packages/tsconfig-reference/copy/en/categories/Experimental_Options_6177.md b/packages/tsconfig-reference/copy/en/categories/Experimental_Options_6177.md index e7059d72158b..4df3bf949446 100644 --- a/packages/tsconfig-reference/copy/en/categories/Experimental_Options_6177.md +++ b/packages/tsconfig-reference/copy/en/categories/Experimental_Options_6177.md @@ -2,4 +2,8 @@ display: "Experimental" --- -Additional Checks Copy +TypeScript strives to only include features which are confirmed to be added into the JavaScript language. + +There have been cases where a feature is compelling enough to be an exception to that rule, and these live as experimental compiler flags. +It is possible that a version of these features may be different when/if they are added to the JavaScript language, and thus are considered risky. + diff --git a/packages/tsconfig-reference/copy/en/categories/Project_Files_0.md b/packages/tsconfig-reference/copy/en/categories/Project_Files_0.md index f5d4c6ec2363..6314c17f2166 100644 --- a/packages/tsconfig-reference/copy/en/categories/Project_Files_0.md +++ b/packages/tsconfig-reference/copy/en/categories/Project_Files_0.md @@ -1,5 +1,5 @@ --- -display: "Project File Inclusion" +display: "File Inclusion" --- - +These settings help you ensure that TypeScript picks up the right files. diff --git a/packages/tsconfig-reference/copy/en/categories/Source_Map_Options_6175.md b/packages/tsconfig-reference/copy/en/categories/Source_Map_Options_6175.md index 0966e1011407..d6ba2e2617d4 100644 --- a/packages/tsconfig-reference/copy/en/categories/Source_Map_Options_6175.md +++ b/packages/tsconfig-reference/copy/en/categories/Source_Map_Options_6175.md @@ -2,4 +2,7 @@ display: "Source Maps" --- -Additional Checks Copy +In order to provide rich debugging tools and crash reports which make sense to developers, TypeScript supports +emitting additional files which conform to the JavaScript Source Map standards. + +These are emitted as `.map` files which live alongside the file they represent. diff --git a/packages/tsconfig-reference/copy/en/categories/Strict_Type_Checking_Options_6173.md b/packages/tsconfig-reference/copy/en/categories/Strict_Type_Checking_Options_6173.md index 391aec5619dc..c6c23991ac56 100644 --- a/packages/tsconfig-reference/copy/en/categories/Strict_Type_Checking_Options_6173.md +++ b/packages/tsconfig-reference/copy/en/categories/Strict_Type_Checking_Options_6173.md @@ -2,4 +2,12 @@ display: "Strict Checks" --- -Additional Checks Copy +TypeScript supports a spectrum of JavaScript patterns, TypeScript patterns and strives for backwards compatibility with them all. + +Upgrading to a new version of TypeScript can uncover two types of errors: + +- Errors which already exist in your codebase, TypeScript has uncovered because the language has become refined it's understanding of JavaScript. +- A new suite of errors which tackle a whole new problem domain. + +TypeScript will usually add a compiler flag for the latter set of errors, and by default these are not enabled. +If you want to ensure that your codebase is as correct as possible, then use the option [`strict`](#strict) to opt-in to every possible improvement as they are built. diff --git a/packages/tsconfig-reference/copy/en/options/allowJs.md b/packages/tsconfig-reference/copy/en/options/allowJs.md index 34c9020aad97..25ae5da72b33 100644 --- a/packages/tsconfig-reference/copy/en/options/allowJs.md +++ b/packages/tsconfig-reference/copy/en/options/allowJs.md @@ -2,4 +2,41 @@ display: "Allow JS" --- -Allow javascript files to be compiled. +Allow JavaScript files to be imported inside your project, instead of just `.ts` and `.tsx` files. For example, this JS file: + +```js twoslasher +// @filename: card.js +export const defaultCardDeck = "Heart" +``` + +When imported into a TypeScript file will raise an error: + +```ts twoslasher +// @errors: 2307 +// @filename: card.js +module.exports.defaultCardDeck = "Heart" + +// ---cut--- +// @filename: index.ts +import { defaultCardDeck } from "./card" + +console.log(defaultCardDeck) +``` + +Imports fine with `allowJs` enabled: + +```ts twoslasher +// @filename: card.js +/// + +module.exports.defaultCardDeck = "Heart" + +// ---cut--- +// @allowJs +// @filename: index.ts +import { defaultCardDeck } from "./card" + +console.log(defaultCardDeck) +``` + +This flag can be used as a way to incrementally add TypeScript files into JS projects by allowing the `.ts` and `.tsx` files to live along-side existing JavaScript files. diff --git a/packages/tsconfig-reference/copy/en/options/allowSyntheticDefaultImports.md b/packages/tsconfig-reference/copy/en/options/allowSyntheticDefaultImports.md index d62cb1bd412a..8aa787c9ef74 100644 --- a/packages/tsconfig-reference/copy/en/options/allowSyntheticDefaultImports.md +++ b/packages/tsconfig-reference/copy/en/options/allowSyntheticDefaultImports.md @@ -2,4 +2,21 @@ display: "Allow Synthetic Default Imports" --- -Allow default imports from modules with no default export. This does not affect code emit, just typechecking. +When set to true, `allowSyntheticDefaultImports` let's you write an import like: + +```ts +import React from "react" +``` + +instead of: + +```ts +import * as React from "react" +``` + +When the module **does not** specify a default export. + +This does not affect the JavaScript emitted by TypeScript, it only for the type checking. +This option brings the behavior of TypeScript in-line with Babel, where extra code is emitted to make using a default export of a module more ergonomic. + + diff --git a/packages/tsconfig-reference/copy/en/options/allowUmdGlobalAccess.md b/packages/tsconfig-reference/copy/en/options/allowUmdGlobalAccess.md index c583f6f17f91..a29f1cf5f65d 100644 --- a/packages/tsconfig-reference/copy/en/options/allowUmdGlobalAccess.md +++ b/packages/tsconfig-reference/copy/en/options/allowUmdGlobalAccess.md @@ -2,4 +2,6 @@ display: "Allow Umd Global Access" --- -Allow accessing UMD globals from modules. +When set to true, `allowUmdGlobalAccess` lets you access UMD exports as globals from inside module files. A module file is a file that has imports and/or exports. Without this flag, using an export from a UMD module requires an import declaration. + +An example use case for this flag would be a web project where you know the particular library (like jQuery or Lodash) will always be available at runtime, but you can’t access it with an import. diff --git a/packages/tsconfig-reference/copy/en/options/allowUnreachableCode.md b/packages/tsconfig-reference/copy/en/options/allowUnreachableCode.md index 36567c42eb4f..47230b7f3a29 100644 --- a/packages/tsconfig-reference/copy/en/options/allowUnreachableCode.md +++ b/packages/tsconfig-reference/copy/en/options/allowUnreachableCode.md @@ -2,10 +2,24 @@ display: "Allow Unreachable Code" --- -Disables warnings about unreachable code. -These warnings are only about code which is provably unreachable due to syntactic construction, like the example below. +Set to false to disable warnings about unreachable code. +These warnings are only about code which is provably unreachable due to the use of JavaScript syntax, for example: ```ts +function fn(n: number) { + if (n > 5) { + return true; + } else { + return false; + } + return true; +} +``` + +With `"allowUnreachableCode": false`: + +```ts twoslasher +// @errors: 7027 // @allowUnreachableCode: false function fn(n: number) { if (n > 5) { @@ -17,4 +31,4 @@ function fn(n: number) { } ``` -TypeScript doesn't error on the basis of code which *appears* to be unreachable due to type analysis. +This does not affect errors on the basis of code which *appears* to be unreachable due to type analysis. diff --git a/packages/tsconfig-reference/copy/en/options/allowUnusedLabels.md b/packages/tsconfig-reference/copy/en/options/allowUnusedLabels.md index fe5d7ef1ca9e..637aecf6dd4e 100644 --- a/packages/tsconfig-reference/copy/en/options/allowUnusedLabels.md +++ b/packages/tsconfig-reference/copy/en/options/allowUnusedLabels.md @@ -2,16 +2,18 @@ display: "Allow Unused Labels" --- -Disables warnings about unused labels. +Set to false to disable warnings about unused labels. + Labels are very rare in JavaScript and typically indicate an attempt to write an object literal: -```ts +```ts twoslash +// @errors: 7028 // @allowUnusedLabels: false -function f(a: number) { - // Forgot 'return' statement! - if (a > 10) +function verifyAge(age: number) { + // Forgot 'return' statement + if (age > 18) { - m: 0 + verified: true } } ``` diff --git a/packages/tsconfig-reference/copy/en/options/alwaysStrict.md b/packages/tsconfig-reference/copy/en/options/alwaysStrict.md index 68ede9dfcba0..4d2400775184 100644 --- a/packages/tsconfig-reference/copy/en/options/alwaysStrict.md +++ b/packages/tsconfig-reference/copy/en/options/alwaysStrict.md @@ -2,4 +2,6 @@ display: "Always Strict" --- -Parse in strict mode and emit "use strict" for each source file. +Ensures that your files are parsed in the ECMAScript strict mode, and emit "use strict" for each source file. + +[ECMAScript strict](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) mode was introduced in ES5 and provides behavior tweaks to the runtime of the JavaScript engine to improve performance, and makes a set of errors throw instead of silently ignoring them. diff --git a/packages/tsconfig-reference/copy/en/options/baseUrl.md b/packages/tsconfig-reference/copy/en/options/baseUrl.md index 48d571a042fc..d0b3b9612d23 100644 --- a/packages/tsconfig-reference/copy/en/options/baseUrl.md +++ b/packages/tsconfig-reference/copy/en/options/baseUrl.md @@ -2,4 +2,25 @@ display: "Base Url" --- -Base directory to resolve non-absolute module names. +Lets you set a base directory to resolve non-absolute module names. + +You can define a root folder where you can do absolute file resolution. E.g. + +``` +baseUrl +├── ex.ts +├── hello +│ └── world.ts +└── tsconfig.json +``` + +With `"baseUrl": "./"` inside this project TypeScript will look for files starting at the same folder as the `tsconfig.json`. + +```ts +import { helloWorld } from "hello/world" + +console.log(helloWorld) +``` + +If you get tired of imports always looking like `"../"` or `"./"`. Or needing +to change as you move files, this is a great way to fix that. diff --git a/packages/tsconfig-reference/copy/en/options/charset.md b/packages/tsconfig-reference/copy/en/options/charset.md index 6539146bb303..1831fd40d2ce 100644 --- a/packages/tsconfig-reference/copy/en/options/charset.md +++ b/packages/tsconfig-reference/copy/en/options/charset.md @@ -2,7 +2,5 @@ display: "Charset" --- -> ❌ **Deprecated:** This option does nothing. - In prior versions of TypeScript, this controlled what encoding was used when reading text files from disk. Today, TypeScript assumes UTF-8 encoding, but will correctly detect UTF-16 (BE and LE) or UTF-8 BOMs. diff --git a/packages/tsconfig-reference/copy/en/options/checkJs.md b/packages/tsconfig-reference/copy/en/options/checkJs.md index 7ba45e80bfb9..7c7ceb71d7ca 100644 --- a/packages/tsconfig-reference/copy/en/options/checkJs.md +++ b/packages/tsconfig-reference/copy/en/options/checkJs.md @@ -1,5 +1,41 @@ --- -display: "Check JS" +display: 'Check JS' --- -Report errors in .js files. +Works in tandem with `allowJs`. When `checkJs` is enabled then errors are reported in JavaScript files. This is +the equivalent of including `// @ts-check` at the top of all JavaScript files which are included in your project. + +For example, this is incorrect JavaScript according to the `parseFloat` type definition which comes with TypeScript: + +```js +// parseFloat only takes a string +module.exports.pi = parseFloat(3.124) +``` + +When imported into a TypeScript module: + +```ts twoslash +// @allowJs +// @filename: constants.js +/// +module.exports.pi = parseFloat(3.124) + +// @filename: index.ts +import { pi } from './constants' +console.log(pi) +``` + +You will not get any errors. However, if you turn on `checkJs` then you will get error messages from the JavaScript file. + +```ts twoslash +// @errors: 2345 +// @allowjs: true +// @checkjs: true +// @filename: constants.js +/// +module.exports.pi = parseFloat(3.124) + +// @filename: index.ts +import { pi } from './constants' +console.log(pi) +``` diff --git a/packages/tsconfig-reference/copy/en/options/composite.md b/packages/tsconfig-reference/copy/en/options/composite.md index 80658918bb9b..b1230d2757df 100644 --- a/packages/tsconfig-reference/copy/en/options/composite.md +++ b/packages/tsconfig-reference/copy/en/options/composite.md @@ -2,10 +2,15 @@ display: "Composite" --- -The `composite` option enforces certain constraints that make it possible for build tools (including TypeScript itself, under `--build` mode) to quickly determine if a project has been built yet. +The `composite` option enforces certain constraints which make it possible for build tools (including TypeScript +itself, under `--build` mode) to quickly determine if a project has been built yet. When this setting is on: * The `rootDir` setting, if not explicitly set, defaults to the directory containing the `tsconfig.json` file. + * All implementation files must be matched by an `include` pattern or listed in the `files` array. If this constraint is violated, `tsc` will inform you which files weren't specified. + * `declaration` defaults to `true` + +You can find documentation on TypeScript projects in [the handbook](https://www.typescriptlang.org/docs/handbook/project-references.html). diff --git a/packages/tsconfig-reference/copy/en/options/declaration.md b/packages/tsconfig-reference/copy/en/options/declaration.md index 82247fcacacb..45d02b87734c 100644 --- a/packages/tsconfig-reference/copy/en/options/declaration.md +++ b/packages/tsconfig-reference/copy/en/options/declaration.md @@ -2,4 +2,29 @@ display: "Declaration" --- -Generates corresponding '.d.ts' file. +Generate `d.ts` files for every TypeScript or JavaScript file inside your project. +These `d.ts` files are type definition files which describe the external API of your module. +With `d.ts` files, tools like TypeScript can provide intellisense and accurate types for un-typed code. + +When `declaration` is set to `true`, running the compiler with this TypeScript code: + +```ts twoslash +export const helloWorld = "hi" +``` + +Will generate an `index.js` file like this: + +```ts twoslash +// @showEmit +export const helloWorld = "hi" +``` + +With a corresponding `helloWorld.d.ts`: + +```js +// @showEmittedFile: index.d.ts +// @showEmit +// @declaration +export declare const helloWorld = "hi"; +``` + diff --git a/packages/tsconfig-reference/copy/en/options/declarationDir.md b/packages/tsconfig-reference/copy/en/options/declarationDir.md index d5f44150b9da..df559b0ff674 100644 --- a/packages/tsconfig-reference/copy/en/options/declarationDir.md +++ b/packages/tsconfig-reference/copy/en/options/declarationDir.md @@ -2,27 +2,34 @@ display: "Declaration Dir" --- -Output directory for generated declaration files. +Offers a way to configure the root directory for where declaration files are emitted. -```ts twoslash -// @errors: 2345 -function longest(a: T, b: T) { - if (a.length >= b.length) { - return a; - } else { - return b; - } -} +``` +example +├── index.ts +├── package.json +└── tsconfig.json +``` -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +with this `tsconfig.json`: -// longerArray is of type 'number[]' -const longerArray = longest([1, 2], [1, 2, 3]); -// longerString is of type 'string' -const longerString = longest("alice", "bob"); -// Error! Numbers don't have a 'length' property -const notOK = longest(10, 100); +```json +{ + "compilerOptions": { + "declaration": true, + "declarationDir": "./types" + } +} +``` + +Would place the d.ts for the `index.ts` in a `types` folder: -const hello = longest("alice", "bob"); -console.log(hello) +``` +example +├── index.js +├── index.ts +├── package.json +├── tsconfig.json +└── types + └── index.d.ts ``` diff --git a/packages/tsconfig-reference/copy/en/options/declarationMap.md b/packages/tsconfig-reference/copy/en/options/declarationMap.md index d487622df8a0..5a8851144cad 100644 --- a/packages/tsconfig-reference/copy/en/options/declarationMap.md +++ b/packages/tsconfig-reference/copy/en/options/declarationMap.md @@ -3,7 +3,7 @@ display: "Declaration Map" --- -Generates a source map for `.d.ts` files that maps back to the original `.ts` source file. +Generates a source map for `.d.ts` files which map back to the original `.ts` source file. This will allow editors such as VS Code to go to the original `.ts` file when using features like *Go to Definition*. You should strongly consider turning this on if you're using project references. diff --git a/packages/tsconfig-reference/copy/en/options/diagnostics.md b/packages/tsconfig-reference/copy/en/options/diagnostics.md index a43ac9dbfde5..075c1284f35b 100644 --- a/packages/tsconfig-reference/copy/en/options/diagnostics.md +++ b/packages/tsconfig-reference/copy/en/options/diagnostics.md @@ -2,4 +2,6 @@ display: "Diagnostics" --- -Show diagnostic information. +Used to output diagnostic information for debugging. This command is a subset of [`extendedDiagnostics`](#extendedDiagnostics) which are more user-facing results, and easier to interpret. + +If you have been asked by a TypeScript compiler engineer to give the results using this flag in a compile, in which there is no harm in using [`--extendedDiagnostics`](#extendedDiagnostics) instead. diff --git a/packages/tsconfig-reference/copy/en/options/disableSizeLimit.md b/packages/tsconfig-reference/copy/en/options/disableSizeLimit.md index 19734f245209..a858eb5eedae 100644 --- a/packages/tsconfig-reference/copy/en/options/disableSizeLimit.md +++ b/packages/tsconfig-reference/copy/en/options/disableSizeLimit.md @@ -2,4 +2,4 @@ display: "Disable Size Limit" --- -Disable size limitations on JavaScript projects. +To avoid a possible memory bloat issue when working with very large JavaScript projects, there is an upper limit to the amount of memory TypeScript will allocate. Turning this flag on will remove the limit. diff --git a/packages/tsconfig-reference/copy/en/options/disableSourceOfProjectReferenceRedirect.md b/packages/tsconfig-reference/copy/en/options/disableSourceOfProjectReferenceRedirect.md index 99df10930f51..6e057112f5ab 100644 --- a/packages/tsconfig-reference/copy/en/options/disableSourceOfProjectReferenceRedirect.md +++ b/packages/tsconfig-reference/copy/en/options/disableSourceOfProjectReferenceRedirect.md @@ -1,6 +1,6 @@ --- display: "Disable Source Project Reference Redirect" -introduced: "3.7" --- -When working with composite TypeScript projects, this option provides a way to go back to the pre-3.7 behavior where d.ts files were used to as the boundaries between modules. In 3.7 the source for truth is now your TypeScript files. +When working with [composite TypeScript projects](/docs/handbook/project-references.html), this option provides a way to go [back to the pre-3.7](/docs/handbook/release-notes/typescript-3-7.html#build-free-editing-with-project-references) behavior where d.ts files were used to as the boundaries between modules. +In 3.7 the source of truth is now your TypeScript files. diff --git a/packages/tsconfig-reference/copy/en/options/downlevelIteration.md b/packages/tsconfig-reference/copy/en/options/downlevelIteration.md index 5567c1656914..3104f39d1e1d 100644 --- a/packages/tsconfig-reference/copy/en/options/downlevelIteration.md +++ b/packages/tsconfig-reference/copy/en/options/downlevelIteration.md @@ -2,7 +2,8 @@ display: "Downlevel Iteration" --- -**Default**: `false`. Has no effect if `target` is ES6 or newer. +Downleveling is TypeScript's term for transpiling to an older version of JavaScript. +This flag is to enable support for a more accurate implementation of how modern JavaScript iterates through new concepts in older JavaScript runtimes. ECMAScript 6 added several new iteration primitives: the `for / of` loop (`for (el of arr)`), Array spread (`[a, ...b]`), argument spread (`fn(...args)`), and `Symbol.iterator`. `--downlevelIteration` allows for these iteration primitives to be used more accurately in ES5 environments if a `Symbol.iterator` implementation is present. @@ -37,7 +38,7 @@ for (const s of str) { } ``` ->> **Note:** Remember, `downlevelIteration` does not improve compliance if `Symbol.iterator` is not present! +>> **Note:** enabling `downlevelIteration` does not improve compliance if `Symbol.iterator` is not present in the runtime. #### Example: Effects on Array Spreads diff --git a/packages/tsconfig-reference/copy/en/options/emitBOM.md b/packages/tsconfig-reference/copy/en/options/emitBOM.md index 15090e5a3504..bb05d4169da2 100644 --- a/packages/tsconfig-reference/copy/en/options/emitBOM.md +++ b/packages/tsconfig-reference/copy/en/options/emitBOM.md @@ -1,5 +1,5 @@ --- -display: "Emit B O M" +display: "Emit BOM" --- Controls whether TypeScript will emit a [byte order mark (BOM)](https://en.wikipedia.org/wiki/Byte_order_mark) when writing output files. diff --git a/packages/tsconfig-reference/copy/en/options/emitDeclarationOnly.md b/packages/tsconfig-reference/copy/en/options/emitDeclarationOnly.md index fe4086b2db24..f665c8009106 100644 --- a/packages/tsconfig-reference/copy/en/options/emitDeclarationOnly.md +++ b/packages/tsconfig-reference/copy/en/options/emitDeclarationOnly.md @@ -4,4 +4,7 @@ display: "Emit Declaration Only" *Only* emit `.d.ts` files; do not emit `.js` files. -This setting is useful if you're using a transpiler other than TypeScript to generate your JavaScript. +This setting is useful in two cases: + +- You are using a transpiler other than TypeScript to generate your JavaScript. +- You are using TypeScript to only generate `d.ts` files for your consumers. diff --git a/packages/tsconfig-reference/copy/en/options/emitDecoratorMetadata.md b/packages/tsconfig-reference/copy/en/options/emitDecoratorMetadata.md index 034f16697442..39346d4cec96 100644 --- a/packages/tsconfig-reference/copy/en/options/emitDecoratorMetadata.md +++ b/packages/tsconfig-reference/copy/en/options/emitDecoratorMetadata.md @@ -2,4 +2,68 @@ display: "Emit Decorator Metadata" --- -Enables experimental support for emitting type metadata for decorators. +Enables experimental support for emitting type metadata for decorators which works with the module [`reflect-metadata`](https://www.npmjs.com/package/reflect-metadata). + +For example, here is the JavaScript + +```ts twoslash +// @experimentalDecorators +function LogMethod(target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) { + console.log(target); + console.log(propertyKey); + console.log(descriptor); +} + +class Demo { + @LogMethod + public foo(bar: number) { + // do nothing + } +} + +const demo = new Demo(); +``` + +With `emitDecoratorMetadata` not set to true (default): + +```ts twoslash +// @experimentalDecorators +// @showEmit +function LogMethod(target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) { + console.log(target); + console.log(propertyKey); + console.log(descriptor); +} + +class Demo { + @LogMethod + public foo(bar: number) { + // do nothing + } +} + +const demo = new Demo(); +``` + +With `emitDecoratorMetadata` set to true: + +```ts twoslash +// @experimentalDecorators +// @showEmit +// @emitDecoratorMetadata +function LogMethod(target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) { + console.log(target); + console.log(propertyKey); + console.log(descriptor); +} + +class Demo { + @LogMethod + public foo(bar: number) { + // do nothing + } +} + +const demo = new Demo(); +``` + diff --git a/packages/tsconfig-reference/copy/en/options/esModuleInterop.md b/packages/tsconfig-reference/copy/en/options/esModuleInterop.md index d85912ccb9a7..5f6e8bb0f794 100644 --- a/packages/tsconfig-reference/copy/en/options/esModuleInterop.md +++ b/packages/tsconfig-reference/copy/en/options/esModuleInterop.md @@ -1,5 +1,42 @@ --- -display: "Es Module Interop" +display: 'Es Module Interop' --- -Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. +Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. + +TypeScript adheres to the EcmaScript standard for modules, which means that a file with exports would have to specifically +include a `default` export in order to support syntax like `import React from "react"`. +This export pattern is rare in modules for CommonJS. For example, without `esModuleInterop` as true: + +```ts twoslash +// @checkJs +// @allowJs +// @allowSyntheticDefaultImports +// @filename: utilFunctions.js +// @noImplicitAny: false +const getStringLength = str => str.length + +module.exports = { + getStringLength, +} + +// @filename: index.ts +import utils from './utilFunctions' + +const count = utils.getStringLength('Check JS') +``` + +This won't work because there isn't a `default` object which you can import. Even though it feels like it should. +For convenience, transpilers like Babel will automatically create a default if one isn't created. Making the module look a bit more like: + +```js +// @filename: utilFunctions.js +const getStringLength = str => str.length +const allFunctions = { + getStringLength, +} + +module.exports = allFunctions +``` + +Turning on this compiler flag will also enable [`allowSyntheticDefaultImports`](#allowSyntheticDefaultImports). diff --git a/packages/tsconfig-reference/copy/en/options/exclude.md b/packages/tsconfig-reference/copy/en/options/exclude.md index 261002b0d5a1..815f538ebea0 100644 --- a/packages/tsconfig-reference/copy/en/options/exclude.md +++ b/packages/tsconfig-reference/copy/en/options/exclude.md @@ -2,10 +2,9 @@ display: "Exclude" --- -**Default**: `["node_modules", "bower_components", "jspm_packages"]`, plus the value of `outDir` if one is specified. - Specifies an array of filenames or patterns that should be skipped when resolving `include`. **Important**: `exclude` *only* changes which files are included as a result of the `include` setting. -A file specified by `exclude` can still become part of your program due to an `import` statement in your code, a `types` inclusion, a `/// + +``` +. +├── scripts ⨯ +│ ├── lint.ts ⨯ +│ ├── update_deps.ts ⨯ +│ └── utils.ts ⨯ +├── src ✓ +│ ├── client ✓ +│ │ ├── index.ts ✓ +│ │ └── utils.ts ✓ +│ ├── server ✓ +│ │ └── index.ts ✓ +├── tests ✓ +│ ├── app.test.ts ✓ +│ ├── utils.ts ✓ +│ └── tests.d.ts ✓ +├── package.json +├── tsconfig.json +└── yarn.lock +``` + `include` and `exclude` support wildcard characters to make glob patterns: - * `*` matches zero or more characters (excluding directory separators) - * `?` matches any one character (excluding directory separators) - * `**/` recursively matches any subdirectory + - `*` matches zero or more characters (excluding directory separators) + - `?` matches any one character (excluding directory separators) + - `**/` matches any directory nested to any level If a glob pattern doesn't include a file extension, then only files with supported extensions are included (e.g. `.ts`, `.tsx`, and `.d.ts` by default, with `.js` and `.jsx` if `allowJs` is set to true). diff --git a/packages/tsconfig-reference/copy/en/options/incremental.md b/packages/tsconfig-reference/copy/en/options/incremental.md index 40f4b0cec2d1..d4b2b0bd1ec0 100644 --- a/packages/tsconfig-reference/copy/en/options/incremental.md +++ b/packages/tsconfig-reference/copy/en/options/incremental.md @@ -2,4 +2,8 @@ display: "Incremental" --- -Enable incremental compilation +Tells TypeScript to save information about the project graph from the last compilation to files stored on disk. This +creates a series of `.tsbuildinfo` files in the same folder as your compilation output. They are not used by your +JavaScript at runtime and can be safely deleted. You can read more about the flag in the [3.4 release notes](/docs/handbook/release-notes/typescript-3-4.html#faster-subsequent-builds-with-the---incremental-flag). + +To control which folders you want to the files to be built to, use the config option [`tsBuildInfoFile`](#tsBuildInfoFile). diff --git a/packages/tsconfig-reference/copy/en/options/inlineSourceMap.md b/packages/tsconfig-reference/copy/en/options/inlineSourceMap.md index 9761013d1d9f..ffc170d9ff88 100644 --- a/packages/tsconfig-reference/copy/en/options/inlineSourceMap.md +++ b/packages/tsconfig-reference/copy/en/options/inlineSourceMap.md @@ -6,4 +6,29 @@ When set, instead of writing out a `.js.map` file to provide source maps, TypeSc Although this results in larger JS files, it can be convenient in some scenarios. For example, you might want to debug JS files on a webserver that doesn't allow `.map` files to be served. -Mutually exclusive with `sourceMap`. +Mutually exclusive with [`sourceMap`](#sourceMap). + +For example, with this TypeScript: + +```ts +const helloWorld = "hi"; +console.log(helloWorld) +``` + +Converts to this JavaScript: + +```ts twoslasher +// @showEmit +const helloWorld = "hi"; +console.log(helloWorld) +``` + +Then enable building it with `inlineSourceMap` enabled there is a comment at the bottom of the file which includes +a source-map for the file. + +```ts twoslasher +// @inlineSourceMap +// @showEmit +const helloWorld = "hi"; +console.log(helloWorld) +``` diff --git a/packages/tsconfig-reference/copy/en/options/inlineSources.md b/packages/tsconfig-reference/copy/en/options/inlineSources.md index 03eb06a84f3e..94f02b765307 100644 --- a/packages/tsconfig-reference/copy/en/options/inlineSources.md +++ b/packages/tsconfig-reference/copy/en/options/inlineSources.md @@ -6,3 +6,31 @@ When set, TypeScript will include the original content of the `.ts` file as an e This is often useful in the same cases as `inlineSourceMap`. Requires either `sourceMap` or `inlineSourceMap` to be set. + + +For example, with this TypeScript: + +```ts +const helloWorld = "hi"; +console.log(helloWorld) +``` + +By default converts to this JavaScript: + +```ts twoslasher +// @showEmit +const helloWorld = "hi"; +console.log(helloWorld) +``` + +Then enable building it with `inlineSources` and `inlineSourceMap` enabled there is a comment at the bottom of the file which includes +a source-map for the file. +Note that the end is different from the example in [`inlineSourceMap`](#inlineSourceMap) because the source-map now contains the original source code also. + +```ts twoslasher +// @inlineSources +// @inlineSourceMap +// @showEmit +const helloWorld = "hi"; +console.log(helloWorld) +``` diff --git a/packages/tsconfig-reference/copy/en/options/isolatedModules.md b/packages/tsconfig-reference/copy/en/options/isolatedModules.md index 4fc9de41cf4a..8b21c40d4219 100644 --- a/packages/tsconfig-reference/copy/en/options/isolatedModules.md +++ b/packages/tsconfig-reference/copy/en/options/isolatedModules.md @@ -13,7 +13,8 @@ It does not change the behavior of your code, or otherwise change the behavior o #### Exports of Non-Value Identifiers In TypeScript, you can import a *type* and then subsequently export it: -```ts + +```ts twoslash // @noErrors import { someType, someFunction } from "someModule"; @@ -35,7 +36,8 @@ Single-file transpilers don't know whether `someType` produces a value or not, s If `isolatedModules` is set, all implementation files must be *modules*. An error occurs if any file isn't a module: -```ts +```ts twoslash +// @errors: 1208 // @isolatedModules function fn() { } ``` @@ -47,6 +49,16 @@ This restriction doesn't apply to `.d.ts` files In TypeScript, when you reference a `const enum` member, the reference is replaced by its actual value in the emitted JavaScript: ```ts +declare const enum Numbers { + Zero = 0, + One = 1 +} +console.log(Numbers.Zero + Numbers.One); +``` + +To: + +```ts twoslash // @showEmit // @removeComments declare const enum Numbers { diff --git a/packages/tsconfig-reference/copy/en/options/jsx.md b/packages/tsconfig-reference/copy/en/options/jsx.md index d2992a071598..4730cf3a4f45 100644 --- a/packages/tsconfig-reference/copy/en/options/jsx.md +++ b/packages/tsconfig-reference/copy/en/options/jsx.md @@ -2,8 +2,6 @@ display: "JSX" --- -**Allowed Values**: `react` (default), `react-native`, `preserve` - Controls how JSX constructs are emitted in JavaScript files. This only affects output of JS files that started in `.tsx` files. diff --git a/packages/tsconfig-reference/copy/en/options/jsxFactory.md b/packages/tsconfig-reference/copy/en/options/jsxFactory.md index 7d9245ef02dd..b31d3ab65753 100644 --- a/packages/tsconfig-reference/copy/en/options/jsxFactory.md +++ b/packages/tsconfig-reference/copy/en/options/jsxFactory.md @@ -1,10 +1,9 @@ --- -display: "JSx Factory" +display: "JSX Factory" --- -**Allowed Values**: Any identifier or dotted identifier; default `"React.createElement"` Changes the function called in `.js` files when compiling JSX Elements. The most common change is to use `"h"` or `"preact.h"` instead of the default `"React.createElement"` if using `preact`. -This is the same as Babel's `/** @jsx h */` directive. +This is the same as [Babel's `/** @jsx h */` directive](https://babeljs.io/docs/en/babel-plugin-transform-react-jsx#custom). diff --git a/packages/tsconfig-reference/copy/en/options/keyofStringsOnly.md b/packages/tsconfig-reference/copy/en/options/keyofStringsOnly.md index f07efbf81d13..97df9811bc20 100644 --- a/packages/tsconfig-reference/copy/en/options/keyofStringsOnly.md +++ b/packages/tsconfig-reference/copy/en/options/keyofStringsOnly.md @@ -2,7 +2,6 @@ display: "Keyof Strings Only" --- -> ❌ **Discouraged:** This flag was provided for backward compatibility reasons and should not be enabled in new or maintained codebases. - This flag changes the `keyof` type operator to return `string` instead of `string | number` when applied to a type with a string index signature. +This flag is used to help people keep this behavior from [before TypeScript 2.9's release](/docs/handbook/release-notes/typescript-2-9.html#support-number-and-symbol-named-properties-with-keyof-and-mapped-types). diff --git a/packages/tsconfig-reference/copy/en/options/lib.md b/packages/tsconfig-reference/copy/en/options/lib.md index ae45755426b2..9007902867e1 100644 --- a/packages/tsconfig-reference/copy/en/options/lib.md +++ b/packages/tsconfig-reference/copy/en/options/lib.md @@ -2,8 +2,6 @@ display: "Lib" --- -**Default**: At a minimum `["dom"]`, plus more depending on `target` - TypeScript includes a default set of type definitions for built-in JS APIs (like `Math`), as well as type definitions for things found in browser environments (like `document`). TypeScript also includes APIs for newer JS features matching the `target` you specify; for example the definition for `Map` is available if `target` is `ES6` or newer. @@ -12,39 +10,58 @@ You may want to change these for a few reasons: * Your runtime platform provides certain JavaScript API objects (maybe through polyfills), but doesn't yet support the full syntax of a given ECMAScript version * You have polyfills or native implementations for some, but not all, of a higher level ECMAScript version -| Name | Contents / Notes | +### High Level libraries + +| Name | Contents | |-------------------------|----------------------------| -| ES5 | Core definitions for all ES3 and ES5 functionality | -| ES2015 | Additional APIs available in ES2015 (also known as ES6) | -| ES6 | Alias for "ES2015" | -| ES2016 | Additional APIs available in ES2016 | -| ES7 | Alias for "ES2016" | -| ES2017 | Additional APIs available in ES2017 | -| ES2018 | Additional APIs available in ES2017 | -| ESNext | Additional APIs available in ESNext | -| DOM | DOM definitions (`window`, `document`, etc.) | -| DOM.Iterable | | -| WebWorker | APIs available in WebWorker contexts | -| ScriptHost | | -| ES2015.Core | | -| ES2015.Collection | | -| ES2015.Generator | | -| ES2015.Iterable | | -| ES2015.Promise | | -| ES2015.Proxy | | -| ES2015.Reflect | | -| ES2015.Symbol | | -| ES2015.Symbol.WellKnown | | -| ES2016.Array.Include | | -| ES2017.object | | -| ES2017.Intl | | -| ES2017.SharedMemory | | -| ES2017.String | | -| ES2017.TypedArrays | | -| ES2018.Intl | | -| ES2018.Promise | | -| ES2018.RegExp | | -| ESNext.AsyncIterable | | -| ESNext.Array | | -| ESNext.Intl | | -| ESNext.Symbol | | +| `ES5` | Core definitions for all ES3 and ES5 functionality | +| `ES2015` | Additional APIs available in ES2015 (also known as ES6) - `array.find`, `Promise`, `Proxy`, `Symbol`, `Map`, `Set`, `Reflect`, etc. | +| `ES6` | Alias for "ES2015" | +| `ES2016` | Additional APIs available in ES2016 - `array.include`, etc. | +| `ES7` | Alias for "ES2016" | +| `ES2017` | Additional APIs available in ES2017 - `Object.entries`, `Object.values`, `Atomics`, `SharedArrayBuffer`, `date.formatToParts`, typed arrays, etc. | +| `ES2018` | Additional APIs available in ES2018 - `async` iterables, `promise.finally`, `Intl.PluralRules`, `rexexp.groups`, etc. | +| `ES2019` | Additional APIs available in ES2019 - `array.flat`, `array.flatMap`, `Object.fromEntries`, `string.trimStart`, `string.trimEnd`, etc. | +| `ES2020` | Additional APIs available in ES2020 - `string.matchAll`, etc. | +| `ESNext` | Additional APIs available in ESNext - This changes as the JavaScript specification evolves | +| `DOM` | [DOM](https://developer.mozilla.org/en-US/docs/Glossary/DOM) definitions - `window`, `document`, etc. | +| `WebWorker` | APIs available in [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) contexts | +| `ScriptHost` | APIs for the [Windows Script Hosting System](https://en.wikipedia.org/wiki/Windows_Script_Host) | + +### Individual library components + +| Name | +|-------------------------| +| `DOM.Iterable` | +| `ES2015.Core` | +| `ES2015.Collection` | +| `ES2015.Generator` | +| `ES2015.Iterable` | +| `ES2015.Promise` | +| `ES2015.Proxy` | +| `ES2015.Reflect` | +| `ES2015.Symbol` | +| `ES2015.Symbol.WellKnown` | +| `ES2016.Array.Include` | +| `ES2017.object` | +| `ES2017.Intl` | +| `ES2017.SharedMemory` | +| `ES2017.String` | +| `ES2017.TypedArrays` | +| `ES2018.Intl` | +| `ES2018.Promise` | +| `ES2018.RegExp` | +| `ES2019.Array` | +| `ES2019.Full` | +| `ES2019.Object` | +| `ES2019.String` | +| `ES2019.Symbol` | +| `ES2020.Full` | +| `ES2020.String` | +| `ES2020.Symbol.wellknown` | +| `ESNext.AsyncIterable` | +| `ESNext.Array` | +| `ESNext.Intl` | +| `ESNext.Symbol` | + +This list may be out of date, you can see the full list in the [TypeScript source code](https://github.com/microsoft/TypeScript/tree/master/lib). diff --git a/packages/tsconfig-reference/copy/en/options/listEmittedFiles.md b/packages/tsconfig-reference/copy/en/options/listEmittedFiles.md index 63d2ba5f4cbb..42899c9708bc 100644 --- a/packages/tsconfig-reference/copy/en/options/listEmittedFiles.md +++ b/packages/tsconfig-reference/copy/en/options/listEmittedFiles.md @@ -2,4 +2,40 @@ display: "List Emitted Files" --- -Print names of generated files part of the compilation. +Print names of generated files part of the compilation to the terminal. + +This flag is useful in two cases: + + - You want to transpile TypeScript as a part of a build chain in the terminal where the filenames are processed in the next command. + - You are not sure that TypeScript has included a file you expected, as a part of debugging the [file inclusion settings](#Project_Files_0). + +For example: + +``` +example +├── index.ts +├── package.json +└── tsconfig.json +``` + +With: + +```json +{ + "compilerOptions": { + "declaration": true, + "listFiles": true + } +} +``` + +Would echo paths like: + +``` +$ npm run tsc + +path/to/example/index.js +path/to/example/index.d.ts +``` + +Normally, TypeScript would return silently on success. diff --git a/packages/tsconfig-reference/copy/en/options/listFiles.md b/packages/tsconfig-reference/copy/en/options/listFiles.md index 0962e0ab81f5..ff84b3760c44 100644 --- a/packages/tsconfig-reference/copy/en/options/listFiles.md +++ b/packages/tsconfig-reference/copy/en/options/listFiles.md @@ -2,4 +2,37 @@ display: "List Files" --- -Print names of files part of the compilation. +Print names of files part of the compilation. This is useful when you are not sure that TypeScript has +included a file you expected. + +For example: + +``` +example +├── index.ts +├── package.json +└── tsconfig.json +``` + +With: + +```json +{ + "compilerOptions": { + "listFiles": true + } +} +``` + +Would echo paths like: + +``` +$ npm run tsc +path/to/example/node_modules/typescript/lib/lib.d.ts +path/to/example/node_modules/typescript/lib/lib.es5.d.ts +path/to/example/node_modules/typescript/lib/lib.dom.d.ts +path/to/example/node_modules/typescript/lib/lib.webworker.importscripts.d.ts +path/to/example/node_modules/typescript/lib/lib.scripthost.d.ts +path/to/example/index.ts +``` + diff --git a/packages/tsconfig-reference/copy/en/options/locale.md b/packages/tsconfig-reference/copy/en/options/locale.md index 9c5e59fb2b4e..edcaa7733d0e 100644 --- a/packages/tsconfig-reference/copy/en/options/locale.md +++ b/packages/tsconfig-reference/copy/en/options/locale.md @@ -2,4 +2,25 @@ display: "Locale" --- -The locale used when displaying messages to the user (e.g. 'en-us') +TypeScript supports a number of languages, however this cannot be set via the `tsconfig.json`, only +via the host environment or the CLI flag `--locale`. E.g. `tsc --locale ru`. + +### Locales supported as of TypeScript 3.7 + +| Name | Locale | +|-------------------------|---------| +| Brazilian Portuguese | `pr-BR` | +| Chinese (Simplified) | `zh-TW` | +| Chinese (Traditional) | `zh-CN` | +| Czech | `cs-CZ` | +| English (US) | `en-US` | +| French | `fr-FR` | +| German | `de-DE` | +| Italian | `it-IT` | +| Japanese | `ja-JP` | +| Korean | `ko-KR` | +| Polish | `pl-PL` | +| Russian | `ru-RU` | +| Spanish | `es-ES` | +| Turkish | `tr-TR` | + diff --git a/packages/tsconfig-reference/copy/en/options/mapRoot.md b/packages/tsconfig-reference/copy/en/options/mapRoot.md index 5550e8fb2d96..3e13559be54e 100644 --- a/packages/tsconfig-reference/copy/en/options/mapRoot.md +++ b/packages/tsconfig-reference/copy/en/options/mapRoot.md @@ -3,3 +3,15 @@ display: "Map Root" --- Specify the location where debugger should locate map files instead of generated locations. +This string is treated verbatim inside the source-map, for example: + +```json +{ + "compilerOptions": { + "sourceMap": true, + "mapRoot": "https://my-website.com/debug/sourcemaps/" + } +} +``` + +Would declare that `index.js` will have sourcemaps at `https://my-website.com/debug/sourcemaps/index.js.map`. diff --git a/packages/tsconfig-reference/copy/en/options/maxNodeModuleJsDepth.md b/packages/tsconfig-reference/copy/en/options/maxNodeModuleJsDepth.md index df74100d0fbf..8c7ae336feb7 100644 --- a/packages/tsconfig-reference/copy/en/options/maxNodeModuleJsDepth.md +++ b/packages/tsconfig-reference/copy/en/options/maxNodeModuleJsDepth.md @@ -2,4 +2,9 @@ display: "Max Node Module JS Depth" --- -The maximum dependency depth to search under node_modules and load JavaScript files. +The maximum dependency depth to search under `node_modules` and load JavaScript files. + +This flag is can only be used when [`allowJs`](#allowJs) is enabled, and is used if you want to have TypeScript infer types for all of the JavaScript inside your `node_modules`. + +Ideally this should stay at 0 (the default), and `d.ts` files should be used to explicitly define the shape of modules. +However, there are cases where you may want to turn this on at the expense of speed and potential accuracy. diff --git a/packages/tsconfig-reference/copy/en/options/module.md b/packages/tsconfig-reference/copy/en/options/module.md index 665925eb56e2..008da1a65a66 100644 --- a/packages/tsconfig-reference/copy/en/options/module.md +++ b/packages/tsconfig-reference/copy/en/options/module.md @@ -2,6 +2,4 @@ display: "Module" --- -**Allowed Values**: `CommonJS` (default if `target` is `ES3` or `ES5`), `ES6`/`ES2015` (synonymous, default for `target` `ES6` and higher), `None`, `UMD`, `AMD`, `System`, `ESNext` - Sets the module system for the program. See the [[Modules]] chapter for more information. diff --git a/packages/tsconfig-reference/copy/en/options/moduleResolution.md b/packages/tsconfig-reference/copy/en/options/moduleResolution.md index 577a1e30fbee..8ce458b7b629 100644 --- a/packages/tsconfig-reference/copy/en/options/moduleResolution.md +++ b/packages/tsconfig-reference/copy/en/options/moduleResolution.md @@ -2,4 +2,4 @@ display: "Module Resolution" --- -Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). +Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). You probably won't need to use this. diff --git a/packages/tsconfig-reference/copy/en/options/noEmit.md b/packages/tsconfig-reference/copy/en/options/noEmit.md index b37fa40d0011..7885db94c071 100644 --- a/packages/tsconfig-reference/copy/en/options/noEmit.md +++ b/packages/tsconfig-reference/copy/en/options/noEmit.md @@ -2,4 +2,8 @@ display: "No Emit" --- -Do not emit outputs. +Do not emit compiler output files like JavaScript source code, source-maps or declarations. + +This makes room for another tool like [Babel](https://babeljs.io), or [swc](https://github.com/swc-project/swc) to handle converting the TypeScript file to a file which can run inside a JavaScript environment. + +You can then use TypeScript as a tool for providing editor integration, and as a source code type-checker. diff --git a/packages/tsconfig-reference/copy/en/options/noEmitHelpers.md b/packages/tsconfig-reference/copy/en/options/noEmitHelpers.md index 5b4643080748..d1339294e782 100644 --- a/packages/tsconfig-reference/copy/en/options/noEmitHelpers.md +++ b/packages/tsconfig-reference/copy/en/options/noEmitHelpers.md @@ -2,4 +2,36 @@ display: "No Emit Helpers" --- -Do not generate custom helper functions like '__extends' in compiled output. +Instead of importing helpers with [`importHelpers`](#importHelpers), you can provide implementations in the global scope for the helpers you use and completely turn off emitting of helper functions. + +For example, using this `async` function in ES5 requires a `await`-like function and `generator`-like function to run: + +```ts twoslash +const getAPI = async (url: string) => { + // Get API + return {} +} +``` + +Which creates quite a lot of JavaScript: + +```ts twoslash +// @showEmit +// @target: ES5 +const getAPI = async (url: string) => { + // Get API + return {} +} +``` + +Which can be switched out with your own globals via this flag: + +```ts twoslash +// @showEmit +// @target: ES5 +// @noEmitHelpers +const getAPI = async (url: string) => { + // Get API + return {} +} +``` diff --git a/packages/tsconfig-reference/copy/en/options/noEmitOnError.md b/packages/tsconfig-reference/copy/en/options/noEmitOnError.md index 8b33d94d8c5e..6918f67ddc8e 100644 --- a/packages/tsconfig-reference/copy/en/options/noEmitOnError.md +++ b/packages/tsconfig-reference/copy/en/options/noEmitOnError.md @@ -2,4 +2,6 @@ display: "No Emit On Error" --- -Do not emit outputs if any errors were reported. +Do not emit compiler output files like JavaScript source code, source-maps or declarations if any errors were reported. + +This defaults to `false`, making it easier to work with TypeScript in a watch-like environment where you may want to see results of changes to your code in another environment before making sure all errors are resolved. diff --git a/packages/tsconfig-reference/copy/en/options/noErrorTruncation.md b/packages/tsconfig-reference/copy/en/options/noErrorTruncation.md index 289b0812062a..d0f5e31dbedc 100644 --- a/packages/tsconfig-reference/copy/en/options/noErrorTruncation.md +++ b/packages/tsconfig-reference/copy/en/options/noErrorTruncation.md @@ -2,4 +2,44 @@ display: "No Error Truncation" --- +TODO: Declare deprecated?! + Do not truncate error messages. + +With `false` + +```ts twoslash +// @noErrorTruncation: false +// @errors: 2322 2454 +var x: { + propertyWithAnExceedinglyLongName1: string; + propertyWithAnExceedinglyLongName2: string; + propertyWithAnExceedinglyLongName3: string; + propertyWithAnExceedinglyLongName4: string; + propertyWithAnExceedinglyLongName5: string; +}; + +// String representation of type of 'x' should be truncated in error message +var s: string = x; +``` + +
+
+
+ +With `true` + +```ts twoslash +// @errors: 2322 2454 +// @noErrorTruncation: true +var x: { + propertyWithAnExceedinglyLongName1: string; + propertyWithAnExceedinglyLongName2: string; + propertyWithAnExceedinglyLongName3: string; + propertyWithAnExceedinglyLongName4: string; + propertyWithAnExceedinglyLongName5: string; +}; + +// String representation of type of 'x' should be truncated in error message +var s: string = x; +``` diff --git a/packages/tsconfig-reference/copy/en/options/noFallthroughCasesInSwitch.md b/packages/tsconfig-reference/copy/en/options/noFallthroughCasesInSwitch.md index 1df2b5c5f869..ba459d1015e5 100644 --- a/packages/tsconfig-reference/copy/en/options/noFallthroughCasesInSwitch.md +++ b/packages/tsconfig-reference/copy/en/options/noFallthroughCasesInSwitch.md @@ -1,5 +1,21 @@ --- -display: "No Fallthrough Cases In Switch" +display: 'No Fallthrough Cases In Switch' --- Report errors for fallthrough cases in switch statement. +Ensures that any non-empty case inside a switch statement includes either `break` or `return`. +This means you won't accidentally ship a case fallthrough bug. + +```ts twoslash +// @noFallthroughCasesInSwitch +// @errors: 7029 +const a: number = 6 + +switch (a) { + case 0: + console.log('even') + case 1: + console.log('odd') + break +} +``` diff --git a/packages/tsconfig-reference/copy/en/options/noImplicitAny.md b/packages/tsconfig-reference/copy/en/options/noImplicitAny.md index 683f0004521c..4429d1508120 100644 --- a/packages/tsconfig-reference/copy/en/options/noImplicitAny.md +++ b/packages/tsconfig-reference/copy/en/options/noImplicitAny.md @@ -2,14 +2,11 @@ display: "No Implicit Any" --- -> ✅ We strongly recommend enabling this in all codebases +In some cases where no type annotations are present, TypeScript will fall back to a type of `any` for a variable when it cannot infer the type. -**Default**: `false`, unless `strict` is set +This can cause some errors to be missed, for example: -In some cases where no type annotations are present, TypeScript will fall back to a type of `any` for a variable. -This can cause some errors to be missed: - -```ts +```ts twoslash // @noImplicitAny: false function fn(s) { // No error? @@ -18,8 +15,10 @@ function fn(s) { fn(42); ``` -When `noImplicitAny` is set, TypeScript will issue an error whenever it would have inferred `any`: -```ts +Turning on `noImplicitAny` however TypeScript will issue an error whenever it would have inferred `any`: + +```ts twoslash +// @errors: 7006 function fn(s) { console.log(s.subtr(3)) } diff --git a/packages/tsconfig-reference/copy/en/options/noImplicitReturns.md b/packages/tsconfig-reference/copy/en/options/noImplicitReturns.md index 1b0873d51e8d..f3828960f021 100644 --- a/packages/tsconfig-reference/copy/en/options/noImplicitReturns.md +++ b/packages/tsconfig-reference/copy/en/options/noImplicitReturns.md @@ -2,4 +2,15 @@ display: "No Implicit Returns" --- -Report error when not all code paths in function return a value. +When enabled, TypeScript will check all code paths in a function to ensure they return a value. + +```ts twoslash +// @errors: 2366 2322 +function lookupHeadphonesManufacturer(color: "blue" | "black"): string { + if ( color === "blue") { + return "beats" + } else { + "bose" + } +} +``` diff --git a/packages/tsconfig-reference/copy/en/options/noImplicitThis.md b/packages/tsconfig-reference/copy/en/options/noImplicitThis.md index bc73f97ac3e7..70b6dcaa55cf 100644 --- a/packages/tsconfig-reference/copy/en/options/noImplicitThis.md +++ b/packages/tsconfig-reference/copy/en/options/noImplicitThis.md @@ -3,3 +3,25 @@ display: "No Implicit This" --- Raise error on 'this' expressions with an implied 'any' type. + +For example, the class below returns a function which tries to access `this.width` and `this.height` – but the context +for `this` inside the function inside `getAreaFunction` is not the instance of the Rectangle. + +```ts twoslash +// @errors: 2683 +class Rectangle { + width: number + height: number + + constructor(width: number, height: number) { + this.width = width; + this.height = height; + } + + getAreaFunction() { + return function() { + return this.width * this.height; + }; + } +} +``` diff --git a/packages/tsconfig-reference/copy/en/options/noImplicitUseStrict.md b/packages/tsconfig-reference/copy/en/options/noImplicitUseStrict.md index e4fa08a97ab5..414784b05433 100644 --- a/packages/tsconfig-reference/copy/en/options/noImplicitUseStrict.md +++ b/packages/tsconfig-reference/copy/en/options/noImplicitUseStrict.md @@ -2,12 +2,10 @@ display: "No Implicit Use Strict" --- -> 🧙‍ You shouldn't need this +You shouldn't need this. By default, when emitting a module file to a non-ES6 target, TypeScript emits a `"use strict";` prologue at the top of the file. +This setting disables the prologue. -By default, when emitting a module file to a non-ES6 target, TypeScript emits a `"use strict";` prologue at the top of the file. -This setting disables that. - -```ts +```ts twoslash // @showEmit // @target: ES3 // @module: AMD @@ -15,7 +13,7 @@ This setting disables that. export function fn() { } ``` -```ts +```ts twoslash // @showEmit // @target: ES3 // @module: AMD diff --git a/packages/tsconfig-reference/copy/en/options/noResolve.md b/packages/tsconfig-reference/copy/en/options/noResolve.md index 8ccac5bd125b..07699c4e578f 100644 --- a/packages/tsconfig-reference/copy/en/options/noResolve.md +++ b/packages/tsconfig-reference/copy/en/options/noResolve.md @@ -2,8 +2,6 @@ display: "No Resolve" --- -> 🧙 This option is rarely used. - By default, TypeScript will examine the initial set of files for `import` and ` { + const defaultModelID = 23 + return { type: "keyboard", modelID } +} +``` diff --git a/packages/tsconfig-reference/copy/en/options/noUnusedParameters.md b/packages/tsconfig-reference/copy/en/options/noUnusedParameters.md index 7b94ebb870e0..7d558ecd9373 100644 --- a/packages/tsconfig-reference/copy/en/options/noUnusedParameters.md +++ b/packages/tsconfig-reference/copy/en/options/noUnusedParameters.md @@ -2,4 +2,13 @@ display: "No Unused Parameters" --- -Report errors on unused parameters. +Report errors on unused parameters in functions. + +```ts twoslash +// @noUnusedLocals +// @errors: 6133 +const createDefaultKeyboard = (modelID: number) => { + const defaultModelID = 23 + return { type: "keyboard", modelID: defaultModelID } +} +``` diff --git a/packages/tsconfig-reference/copy/en/options/out.md b/packages/tsconfig-reference/copy/en/options/out.md index c4facdc9a5b0..255e6d1f5eca 100644 --- a/packages/tsconfig-reference/copy/en/options/out.md +++ b/packages/tsconfig-reference/copy/en/options/out.md @@ -2,7 +2,7 @@ display: "Out" --- ->> ❌ **Deprecated:** Do not use this. Use [[outFile]] instead +Use [outFile](#outfile) instead. The `out` option computes the final file location in a way that is not predictable or consistent. -This option is retained for backward compatibility only. +This option is retained for backward compatibility only and is deprecated. diff --git a/packages/tsconfig-reference/copy/en/options/outDir.md b/packages/tsconfig-reference/copy/en/options/outDir.md index 0526e07b7136..383d9b74837f 100644 --- a/packages/tsconfig-reference/copy/en/options/outDir.md +++ b/packages/tsconfig-reference/copy/en/options/outDir.md @@ -3,7 +3,11 @@ display: "Out Dir" --- If specified, `.js` (as well as `.d.ts`, `.js.map`, etc.) files will be emitted in the specified directory. -The directory structure of the original source files is preserved; see [[rootDir]] if the computed root is not what you intended. +The directory structure of the original source files is preserved; see [rootDir](#rootDir) if the computed root is not what you intended. + +``` + +``` If not specified, `.js` files will be emitted in the same directory as the `.ts` files they were generated from. diff --git a/packages/tsconfig-reference/copy/en/options/paths.md b/packages/tsconfig-reference/copy/en/options/paths.md index b9b709d4db7f..6998d969ce06 100644 --- a/packages/tsconfig-reference/copy/en/options/paths.md +++ b/packages/tsconfig-reference/copy/en/options/paths.md @@ -1,5 +1,38 @@ --- -display: "Paths" +display: 'Paths' --- -A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. +A series of entries which re-map imports to lookup locations relative to the `baseUrl`, there is a larger coverage of `paths` in [the handbook](/docs/handbook/module-resolution.html#path-mapping). + +`paths` lets you declare how TypeScript should resolve an import in your `require`/`import`s. + +```json +{ + "compilerOptions": { + "baseUrl": ".", // this must be specified if "paths" is specified. + "paths": { + "jquery": ["node_modules/jquery/dist/jquery"] // this mapping is relative to "baseUrl" + } + } +} +``` + +This would allow you to be able to write `import "jquery"`, and get all of the correct typing locally. + +```json +{ + "compilerOptions": { + "baseUrl": "src", + "paths": { + "app/*": ["app/*"], + "config/*": ["app/_config/*"], + "environment/*": ["environments/*"], + "shared/*": ["app/_shared/*"], + "helpers/*": ["helpers/*"], + "tests/*": ["tests/*"] + }, +} +``` + +In this case, you can tell the TypeScript file resolver to support a number of custom prefixes to find code. +This pattern can be used to avoid long relative paths within your codebase. diff --git a/packages/tsconfig-reference/copy/en/options/plugins.md b/packages/tsconfig-reference/copy/en/options/plugins.md index 9865309c94ef..e11a10be1b92 100644 --- a/packages/tsconfig-reference/copy/en/options/plugins.md +++ b/packages/tsconfig-reference/copy/en/options/plugins.md @@ -2,4 +2,14 @@ display: "Plugins" --- -List of language service plugins. +List of language service plugins to run inside the editor. + +Language service plugins are a way to provide additional information to a user based on existing TypeScript files. They can enhance existing messages between TypeScript and an editor, or to provide their own error messages. + +For example: + + - [ts-sql-plugin](https://github.com/xialvjun/ts-sql-plugin#readme) — Adds SQL linting with a template strings SQL builder. + - [typescript-styled-plugin](https://github.com/Microsoft/typescript-styled-plugin) — Provides CSS linting inside template strings . + - [typescript-eslint-language-service](https://github.com/Quramy/typescript-eslint-language-service) — Provides eslint error messaging and fix-its inside the compiler's output. + +VS Code has the ability for a extension to [automatically include language service plugins](https://code.visualstudio.com/api/references/contribution-points#contributes.typescriptServerPlugins), and so you may have some running in your editor without needing to define them in your `tsconfig.json`. diff --git a/packages/tsconfig-reference/copy/en/options/preserveConstEnums.md b/packages/tsconfig-reference/copy/en/options/preserveConstEnums.md index e39bb7e4a831..d1d2d8107755 100644 --- a/packages/tsconfig-reference/copy/en/options/preserveConstEnums.md +++ b/packages/tsconfig-reference/copy/en/options/preserveConstEnums.md @@ -2,4 +2,56 @@ display: "Preserve Const Enums" --- -Do not erase const enum declarations in generated code. +Do not erase `const enum` declarations in generated code. `const enum`s provide a way to reduce the overall memory footprint +of your application at runtime by emitting the enum value instead of a reference. + +For example with this TypeScript: + +```ts twoslash +const enum Album { + JimmyEatWorldFutures = 1, + TubRingZooHypothesis = 2, + DogFashionDiscoAdultery = 3 +} + +const selectedAlbum = Album.JimmyEatWorldFutures +if (selectedAlbum === Album.JimmyEatWorldFutures) { + console.log("That is a great choice.") +} +``` + +The default `const enum` behavior is to convert any `Album.Something` to the corresponding number literal, and to remove a reference +to the enum from the JavaScript completely. + +```ts twoslash +// @showEmit +const enum Album { + JimmyEatWorldFutures = 1, + TubRingZooHypothesis = 2, + DogFashionDiscoAdultery = 3 +} + +const selectedAlbum = Album.JimmyEatWorldFutures +if (selectedAlbum === Album.JimmyEatWorldFutures) { + console.log("That is a great choice.") +} +``` + +With `preserveConstEnums` set to `true`, the `enum` exists at runtime and the numbers are still emitted. + +```ts twoslash +// @preserveConstEnums: true +// @showEmit +const enum Album { + JimmyEatWorldFutures = 1, + TubRingZooHypothesis = 2, + DogFashionDiscoAdultery = 3 +} + +const selectedAlbum = Album.JimmyEatWorldFutures +if (selectedAlbum === Album.JimmyEatWorldFutures) { + console.log("That is a great choice.") +} +``` + +This essentially makes such `const enums` a source-code feature only, with no runtime traces. diff --git a/packages/tsconfig-reference/copy/en/options/preserveSymlinks.md b/packages/tsconfig-reference/copy/en/options/preserveSymlinks.md index 45b680e32cf6..524015c06235 100644 --- a/packages/tsconfig-reference/copy/en/options/preserveSymlinks.md +++ b/packages/tsconfig-reference/copy/en/options/preserveSymlinks.md @@ -1,5 +1,9 @@ --- -display: "Preserve Symlinks" +display: 'Preserve Symlinks' --- -Do not resolve the real path of symlinks. +This is to reflect the same flag in Node.js; which does not resolve the real path of symlinks. + +This flag also exhibits the opposite behavior to Webpack’s `resolve.symlinks` option (i.e. setting TypeScript’s `preserveSymlinks` to true parallels setting Webpack’s `resolve.symlinks` to false, and vice-versa). + +With this enabled, references to modules and packages (e.g. `import`s and `/// ` directives) are all resolved relative to the location of the symbolic link file, rather than relative to the path that the symbolic link resolves to. diff --git a/packages/tsconfig-reference/copy/en/options/preserveWatchOutput.md b/packages/tsconfig-reference/copy/en/options/preserveWatchOutput.md index 48ca316bd16a..98310a423d7a 100644 --- a/packages/tsconfig-reference/copy/en/options/preserveWatchOutput.md +++ b/packages/tsconfig-reference/copy/en/options/preserveWatchOutput.md @@ -2,4 +2,4 @@ display: "Preserve Watch Output" --- -Whether to keep outdated console output in watch mode instead of clearing the screen. +Whether to keep outdated console output in watch mode instead of clearing the screen every time a change happened. diff --git a/packages/tsconfig-reference/copy/en/options/pretty.md b/packages/tsconfig-reference/copy/en/options/pretty.md index 41bcfe8a9e14..c2c3f91d0cd6 100644 --- a/packages/tsconfig-reference/copy/en/options/pretty.md +++ b/packages/tsconfig-reference/copy/en/options/pretty.md @@ -2,4 +2,5 @@ display: "Pretty" --- -Stylize errors and messages using color and context (experimental). +Stylize errors and messages using color and context, this is on by default — offers you a chance to have less terse, +single colored messages from the compiler. diff --git a/packages/tsconfig-reference/copy/en/options/reactNamespace.md b/packages/tsconfig-reference/copy/en/options/reactNamespace.md index de5b568d8734..acf83ffd406a 100644 --- a/packages/tsconfig-reference/copy/en/options/reactNamespace.md +++ b/packages/tsconfig-reference/copy/en/options/reactNamespace.md @@ -2,4 +2,4 @@ display: "React Namespace" --- -[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit +Use [`--jsxFactory`](#jsxFactory) instead. Specify the object invoked for `createElement` when targeting `react` for TSX files. diff --git a/packages/tsconfig-reference/copy/en/options/references.md b/packages/tsconfig-reference/copy/en/options/references.md index 7f78b6fe02d4..53c15f122882 100644 --- a/packages/tsconfig-reference/copy/en/options/references.md +++ b/packages/tsconfig-reference/copy/en/options/references.md @@ -2,4 +2,8 @@ display: "References" --- -TODO +Project references are a way to structure your TypeScript programs into smaller pieces. +Using Project References can greatly improve build and editor interaction times, enforce logical separation between components, and organize your code in new and improved ways. + +You can read more about how references works in the [Project References](/docs/handbook/project-references.html) section of the handbook + diff --git a/packages/tsconfig-reference/copy/en/options/removeComments.md b/packages/tsconfig-reference/copy/en/options/removeComments.md index 72f9081edabf..6a34f21b95d3 100644 --- a/packages/tsconfig-reference/copy/en/options/removeComments.md +++ b/packages/tsconfig-reference/copy/en/options/removeComments.md @@ -1,5 +1,32 @@ --- -display: "Remove Comments" +display: 'Remove Comments' --- -Do not emit comments to output. +Strips all comments from TypeScript files when converting into JavaScript. Defaults to `true`. + +For example, this is a TypeScript file which has a JSDoc comment: + +```ts +/** The translation of 'Hello world' into Portuguese */ +export const helloWorldPTBR = 'Olá Mundo' +``` + +Without setting `removeComments` or having it as `true`: + +```ts twoslash +// @showEmit +// @removeComments: tru +/** The translation of 'Hello world' into Portuguese */ +export const helloWorldPTBR = 'Olá Mundo' +``` + +When `removeComments` is set to `false`: + +```ts twoslash +// @showEmit +// @removeComments: false +/** The translation of 'Hello world' into Portuguese */ +export const helloWorldPTBR = 'Olá Mundo' +``` + +This means that your comments will show up in the JavaScript code. diff --git a/packages/tsconfig-reference/copy/en/options/resolveJsonModule.md b/packages/tsconfig-reference/copy/en/options/resolveJsonModule.md index e53cb9578833..f3071f4cbb43 100644 --- a/packages/tsconfig-reference/copy/en/options/resolveJsonModule.md +++ b/packages/tsconfig-reference/copy/en/options/resolveJsonModule.md @@ -1,5 +1,38 @@ --- -display: "Resolve JSon Module" +display: 'Resolve JSON Module' --- -Include modules imported with '.json' extension +Allows importing modules with a '.json' extension, which is a common practice in node projects. This includes +generating a type for the `import` based on the static JSON shape. + +TypeScript does not support resolving JSON files by default: + +```ts +// @filename: settings.json +{ + "repo": "TypeScript", + "dry": false, + "debug": false +} +// @filename: index.ts +import settings from "./settings.json"; + +settings.debug === true; +settings.dry === 2; +``` + +Enabling the option allows importing JSON, and validating the types in that JSON file. + +```ts +// @filename: settings.json +{ + "repo": "TypeScript", + "dry": false, + "debug": false +} +// @filename: index.ts +import settings from "./settings.json"; + +settings.debug === true; +settings.dry === 2; +``` diff --git a/packages/tsconfig-reference/copy/en/options/rootDirs.md b/packages/tsconfig-reference/copy/en/options/rootDirs.md index f27382b37898..d64bd9ad1d66 100644 --- a/packages/tsconfig-reference/copy/en/options/rootDirs.md +++ b/packages/tsconfig-reference/copy/en/options/rootDirs.md @@ -2,4 +2,33 @@ display: "Root Dirs" --- -List of root folders whose combined content represents the structure of the project at runtime. +Using `rootDirs`, you can inform the compiler that there are many "virtual" directories acting as a single root. +This allows the compiler to resolve relative module imports within these "virtual" directories, as if they were merged in to one directory. + +For example: + +``` + src + └── views + └── view1.ts (can import "./template1", "./view2`) + └── view2.ts (can import "./template1", "./view1`) + + generated + └── templates + └── views + └── template1.ts (can import "./view1", "./view2") +``` + +```json +{ + "compilerOptions": { + "rootDirs": [ + "src/views", + "generated/templates/views" + ] + } +} +``` + +This does not affect how TypeScript emits JavaScript, it only emulates the assumption that they will be able to +work via those relative paths at runtime. diff --git a/packages/tsconfig-reference/copy/en/options/skipDefaultLibCheck.md b/packages/tsconfig-reference/copy/en/options/skipDefaultLibCheck.md index 8e2bd1af7c6c..b0b851d719a7 100644 --- a/packages/tsconfig-reference/copy/en/options/skipDefaultLibCheck.md +++ b/packages/tsconfig-reference/copy/en/options/skipDefaultLibCheck.md @@ -2,4 +2,4 @@ display: "Skip Default Lib Check" --- -[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files. +Use [`--skipLibCheck`](#skipLibCheck) instead. Skip type checking of default library declaration files. diff --git a/packages/tsconfig-reference/copy/en/options/skipLibCheck.md b/packages/tsconfig-reference/copy/en/options/skipLibCheck.md index 2d1d2e678093..49262297166c 100644 --- a/packages/tsconfig-reference/copy/en/options/skipLibCheck.md +++ b/packages/tsconfig-reference/copy/en/options/skipLibCheck.md @@ -3,3 +3,12 @@ display: "Skip Lib Check" --- Skip type checking of declaration files. + +This can save time during compilation at the expense of type-system accuracy. For example, two libraries could +define two copies of the same `type` in an inconsistent way. Rather than doing a full check of all `d.ts` files, TypeScript +will type check the code you specifically refer to in your app's source code. + +A common case where you might think to use `skipLibCheck` is when there are two copies of a library's types in +your `node_modules`. In these cases, you should consider using a feature like [yarn's resolutions](https://yarnpkg.com/lang/en/docs/selective-version-resolutions/) +to ensure there is only one copy of that dependency in your tree or investigate how to ensure there is +only one copy by understanding the dependency resolution to fix the issue without additional tooling. diff --git a/packages/tsconfig-reference/copy/en/options/sourceMap.md b/packages/tsconfig-reference/copy/en/options/sourceMap.md index f622c14be735..94fef3aec065 100644 --- a/packages/tsconfig-reference/copy/en/options/sourceMap.md +++ b/packages/tsconfig-reference/copy/en/options/sourceMap.md @@ -6,7 +6,25 @@ Enables the generation of [sourcemap files](https://developer.mozilla.org/en-US/ These files allow debuggers and other tools to display the original TypeScript source code when actually working with the emitted JavaScript files. Source map files are emitted as `.js.map` (or `.jsx.map`) files next to the corresponding `.js` output file. -The `.js` files will in turn contain a sourcemap comment to indicate to tools where the files are: +The `.js` files will in turn contain a sourcemap comment to indicate to tools where the files are to external tools, for example: + +```ts +// helloWorld.ts +export declare const helloWorld = "hi"; +``` + +Compiling with `sourceMap` set to `true` creates the following JavaScript file: + ```js -//# sourceMappingURL=main.js.map +// helloWorld.js +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.helloWorld = "hi"; +//# sourceMappingURL=// helloWorld.js.map +``` + +And this also generates this json map: +```json +// helloWorld.js.map +{"version":3,"file":"ex.js","sourceRoot":"","sources":["../ex.ts"],"names":[],"mappings":";;AAAa,QAAA,UAAU,GAAG,IAAI,CAAA"} ``` diff --git a/packages/tsconfig-reference/copy/en/options/sourceRoot.md b/packages/tsconfig-reference/copy/en/options/sourceRoot.md index 38ca232e8f79..a584909d3852 100644 --- a/packages/tsconfig-reference/copy/en/options/sourceRoot.md +++ b/packages/tsconfig-reference/copy/en/options/sourceRoot.md @@ -2,4 +2,16 @@ display: "Source Root" --- -Specify the location where debugger should locate TypeScript files instead of source locations. +Specify the location where a debugger should locate TypeScript files instead of relative source locations. +This string is treated verbatim inside the source-map where you can use a path or a URL: + +```json +{ + "compilerOptions": { + "sourceMap": true, + "sourceRoot": "https://my-website.com/debug/source/" + } +} +``` + +Would declare that `index.js` will have a source file at `https://my-website.com/debug/source/index.ts`. diff --git a/packages/tsconfig-reference/copy/en/options/strict.md b/packages/tsconfig-reference/copy/en/options/strict.md index 10ca54e4a8fc..552318e5be48 100644 --- a/packages/tsconfig-reference/copy/en/options/strict.md +++ b/packages/tsconfig-reference/copy/en/options/strict.md @@ -2,8 +2,6 @@ display: "Strict" --- -> ✅ We recommend enabling this in all codebases, especially new ones - The `strict` flag enables a wide range of type checking behavior that results in stronger guarantees of program correctness. Turning this on is equivalent to enabling all of the *strict mode family* options, which are outlined below. You can then turn off individual strict mode family checks as needed. diff --git a/packages/tsconfig-reference/copy/en/options/strictBindCallApply.md b/packages/tsconfig-reference/copy/en/options/strictBindCallApply.md index 0d8e642691fe..70cefac9cc61 100644 --- a/packages/tsconfig-reference/copy/en/options/strictBindCallApply.md +++ b/packages/tsconfig-reference/copy/en/options/strictBindCallApply.md @@ -6,7 +6,7 @@ display: "Strict Bind Call Apply" When set, TypeScript will check that the built-in methods of functions `call`, `bind`, and `apply` are invoked with correct argument for the underlying function: -```ts +```ts // With strictBindCallApply on function fn(x: string) { return parseInt(x); diff --git a/packages/tsconfig-reference/copy/en/options/strictFunctionTypes.md b/packages/tsconfig-reference/copy/en/options/strictFunctionTypes.md index 9f7fd270e2d1..0be261195e0e 100644 --- a/packages/tsconfig-reference/copy/en/options/strictFunctionTypes.md +++ b/packages/tsconfig-reference/copy/en/options/strictFunctionTypes.md @@ -2,15 +2,11 @@ display: "Strict Function Types" --- -> ✅ We strongly recommend enabling this in all codebases - -**Default**: `false`, unless `strict` is set - When enabled, this flag causes functions parameters to be checked more correctly. -Here's a basic example with `strictFunctionTypes` *off*: +Here's a basic example with `strictFunctionTypes` off: -```ts +```ts twoslash // @strictFunctionTypes: false function fn(x: string) { console.log("Hello, " + x.toLowerCase()); @@ -25,7 +21,9 @@ func(10); ``` With `strictFunctionTypes` *on*, the error is correctly detected: -```ts + +```ts twoslash +// @errors: 2322 function fn(x: string) { console.log("Hello, " + x.toLowerCase()); } @@ -38,10 +36,12 @@ let func: StringOrNumberFunc = fn; During development of this feature, we discovered a large number of inherently unsafe class hierarchies, including some in the DOM. Because of this, the setting only applies to functions written in *function* syntax, not to those in *method* syntax: -```ts + +```ts twoslash type Methodish = { func(x: string | number): void; }; + function fn(x: string) { console.log("Hello, " + x.toLowerCase()); } diff --git a/packages/tsconfig-reference/copy/en/options/strictNullChecks.md b/packages/tsconfig-reference/copy/en/options/strictNullChecks.md index 3ffa2eeb2805..0e51b86000f3 100644 --- a/packages/tsconfig-reference/copy/en/options/strictNullChecks.md +++ b/packages/tsconfig-reference/copy/en/options/strictNullChecks.md @@ -2,9 +2,48 @@ display: "Strict Null Checks" --- -**Default**: `false`, unless `strict` is set - -When `strictNullChecks` is `false`, `null` and `undefined` are considered to be valid values of all types. +When `strictNullChecks` is `false`, `null` and `undefined` are effectively ignored by the language. This can lead to unexpected errors at runtime. When `strictNullChecks` is `true`, `null` and `undefined` have their own distinct types and you'll get a type error if you try to use them where a concrete value is expected. + +For example with this TypeScript code, `users.find` has no guarantee that it will actually find a user, but you can +write code as though it will: + +```ts twoslash +// @strictNullChecks: false +declare const loggedInUsername: string + +const users = [{ name: "Oby", age: 12 }, { name: "Heera", age: 32 }] +const loggedInUser = users.find(u => u.name === loggedInUsername) + +console.log(loggedInUser.age) +``` + +Setting `strictNullChecks` to `true` will raise an error that you have not made a guarantee that the `loggedInUser` exists before trying to use it. + +```ts twoslash +// @errors: 2339 2532 +// @strictNullChecks +declare const loggedInUsername: string + +const users = [{ name: "Oby", age: 12 }, { name: "Heera", age: 32 }] +const loggedInUser = users.find(u => u.name === loggedInUsername) + +console.log(loggedInUser.age) +``` + +The second example failed because the array's `find` function looks a bit like this simplification: + +```ts +// When strictNullChecks: true +type Array = { + find(predicate: (value: any, index: number) => boolean): S | undefined; +} + +// When strictNullChecks: false the undefined is removed from the type system, +// allowing you to write code which assumes it always found a result +type Array = { + find(predicate: (value: any, index: number) => boolean): S; +} +``` diff --git a/packages/tsconfig-reference/copy/en/options/strictPropertyInitialization.md b/packages/tsconfig-reference/copy/en/options/strictPropertyInitialization.md index 7e0a3b4ed378..e4c2c546a457 100644 --- a/packages/tsconfig-reference/copy/en/options/strictPropertyInitialization.md +++ b/packages/tsconfig-reference/copy/en/options/strictPropertyInitialization.md @@ -2,4 +2,27 @@ display: "Strict Property Initialization" --- -When set, it becomes an error to declare a class property without directly initializing it before the end of the constructor. +When set to true, TypeScript will raise an error when a class property was declared but not set in the constructor. + +```ts twoslash +// @errors: 2564 +class UserAccount { + name: string; + accountType = "user"; + + email: string; + address: string | undefined; + + constructor(name: string) { + this.name = name; + // Note that this.email is not set + } +} +``` + +In the above case: + +- `this.name` is set specifically. +- `this.accountType` is set by default. +- `this.email` is not set and raises an error. +- `this.address` is declared as potentially `undefined` which means it does not have to be set. diff --git a/packages/tsconfig-reference/copy/en/options/stripInternal.md b/packages/tsconfig-reference/copy/en/options/stripInternal.md index 4a38ecfb59c3..1ede18139b50 100644 --- a/packages/tsconfig-reference/copy/en/options/stripInternal.md +++ b/packages/tsconfig-reference/copy/en/options/stripInternal.md @@ -2,4 +2,58 @@ display: "Strip Internal" --- -Do not emit declarations for code that has an '@internal' annotation. +Do not emit declarations for code that has an `@internal` annotation in it's JSDoc comment. +This is an internal compiler option; use at your own risk, because the compiler does not check that the result is valid. +If you are searching for a tool to handle additional levels of visibility within your `d.ts` files, look at [api-extractor](https://api-extractor.com). + +```ts twoslash +/** + * Days available in a week + * @internal + */ +export const daysInAWeek = 7; + +/** Gets the */ +export function weeklySalary(dayRate: number) { + return daysInAWeek * dayRate +} +``` + +With the flag set to `false` (default): + +```ts twoslash +// @showEmittedFile: index.d.ts +// @showEmit +// @declaration +/** + * Days available in a week + * @internal + */ +export const daysInAWeek = 7; + +/** Calculate how much someone earns in a week */ +export function weeklySalary(dayRate: number) { + return daysInAWeek * dayRate +} +``` + +With `stripInternal` set to `true` the `d.ts` emitted will be redacted. + +```ts twoslash +// @stripinternal +// @showEmittedFile: index.d.ts +// @showEmit +// @declaration +/** + * Days available in a week + * @internal + */ +export const daysInAWeek = 7; + +/** Calculate how much someone earns in a week */ +export function weeklySalary(dayRate: number) { + return daysInAWeek * dayRate +} +``` + +The JavaScript output is still the same. diff --git a/packages/tsconfig-reference/copy/en/options/suppressExcessPropertyErrors.md b/packages/tsconfig-reference/copy/en/options/suppressExcessPropertyErrors.md index 2af6855f2a33..5bbfc51ae35e 100644 --- a/packages/tsconfig-reference/copy/en/options/suppressExcessPropertyErrors.md +++ b/packages/tsconfig-reference/copy/en/options/suppressExcessPropertyErrors.md @@ -2,11 +2,14 @@ display: "Suppress Excess Property Errors" --- -> ❌ **Discouraged:** This flag is provided for backward compatibility. Consider using `@ts-ignore` instead. +This disables reporting of excess property errors, such as the one shown in the following example: -This disables reporting of excess property errors, such as the one shown in the following example - -```ts +```ts twoslash +// @errors: 2322 type Point = { x: number, y: number }; const p: Point = { x: 1, y: 3, m: 10 }; ``` + +This flag was added to help people migrate to the stricter checking of new object literals in [TypeScript 1.6](/docs/handbook/release-notes/typescript-1-6.html#stricter-object-literal-assignment-checks). + +We don't recommend using this flag in a modern codebase, you can suppress one-off cases where you need it using `// @ts-ignore`. diff --git a/packages/tsconfig-reference/copy/en/options/suppressImplicitAnyIndexErrors.md b/packages/tsconfig-reference/copy/en/options/suppressImplicitAnyIndexErrors.md index 6250a8f00205..c53245affdd4 100644 --- a/packages/tsconfig-reference/copy/en/options/suppressImplicitAnyIndexErrors.md +++ b/packages/tsconfig-reference/copy/en/options/suppressImplicitAnyIndexErrors.md @@ -2,11 +2,22 @@ display: "Suppress Implicit Any Index Errors" --- -> ❌ **Discouraged:** This flag is provided for backward compatibility. Consider using `@ts-ignore` instead. +Turning `noImplicitAny` on suppresses implicit any warning reports when indexing into objects, as shown in the following example: -This disables reporting of implicit `any` warnings when indexing into objects, such as shown in the following example +```ts twoslash +// @noImplicitAny: true +// @strict: true +// @errors: 7053 +const obj = { x: 10 }; +console.log(obj["foo"]); +``` + +Using `suppressImplicitAnyIndexErrors` is quite a drastic approach. It is recommended to use a `@ts-ignore` comment instead: -```ts +```ts twoslash +// @noImplicitAny: true +// @strict: true const obj = { x: 10 }; +// @ts-ignore console.log(obj["foo"]); ``` diff --git a/packages/tsconfig-reference/copy/en/options/target.md b/packages/tsconfig-reference/copy/en/options/target.md index 15d3a17cc9a4..e9394170f680 100644 --- a/packages/tsconfig-reference/copy/en/options/target.md +++ b/packages/tsconfig-reference/copy/en/options/target.md @@ -2,16 +2,24 @@ display: "Target" --- -**Allowed Values**: `ES3` (default), `ES5`, `ES6`/`ES2015` (synonomous), `ES7`/`ES2016`, `ES2017`, `ES2018`, `ES2019`, `ESNext` +Modern browsers support all ES6 features, so `ES6` is a good choice. +You might choose to set a lower target if your code is deployed to older environments, or a higher target if your code is guaranteed to run in newer environments. -All modern browsers support all ES6 features, so `ES6` is a good choice. -You might choose to set a lower target if your code is deployed to older environments, or a higher target if your code only runs on newer environments. - -The `target` setting changes which JS features are downleveled or left intact. +The `target` setting changes which JS features are downleveled and which are left intact. For example, an arrow function `() => this` will be turned into an equivalent `function` expression if `target` is ES5 or lower. -`target` also changes the default value of [[`lib`]]. -You may "mix and match" `target` and `lib` settings as desired. +Changing `target` also changes the default value of [`lib`](#lib). +You may "mix and match" `target` and `lib` settings as desired, but you could just set `target` for convenience. + +If your are only working with Node.js, here are recommended `target` based off of the Node version: + +| Name | Supported Target | +| ------- | -------- | +| Node 8 | `ES2017` | +| Node 10 | `ES2018` | +| Node 12 | `ES2019` | + +These are based on [node.green](https://node.green)'s database of support. -The value `ESNext` refers to whatever the highest version TypeScript supports at the time is. -This setting should be used with caution, since it doesn't mean the same thing between TypeScript versions and can make upgrades less predictable. +The special `ESNext` value refers to the highest version your TypeScript supports. +This setting should be used with caution, since it doesn't mean the same thing between different TypeScript versions and can make upgrades less predictable. diff --git a/packages/tsconfig-reference/copy/en/options/traceResolution.md b/packages/tsconfig-reference/copy/en/options/traceResolution.md index afb3c58bc97d..d6daa8886faf 100644 --- a/packages/tsconfig-reference/copy/en/options/traceResolution.md +++ b/packages/tsconfig-reference/copy/en/options/traceResolution.md @@ -2,4 +2,7 @@ display: "Trace Resolution" --- -Enable tracing of the name resolution process. +When you are trying to debug why a module isn't being included. +You can set `traceResolutions` to `true` to have TypeScript print information about its resolution process for each processed file. + +You can read more about this in [the handbook](/docs/handbook/module-resolution.html#tracing-module-resolution). diff --git a/packages/tsconfig-reference/copy/en/options/tsBuildInfoFile.md b/packages/tsconfig-reference/copy/en/options/tsBuildInfoFile.md index eae628c3ec88..0c470c0ba424 100644 --- a/packages/tsconfig-reference/copy/en/options/tsBuildInfoFile.md +++ b/packages/tsconfig-reference/copy/en/options/tsBuildInfoFile.md @@ -2,4 +2,8 @@ display: "TS Build Info File" --- -Specify file to store incremental compilation information +This setting lets you specify a file for storing incremental compilation information as a part of composite projects which enables faster +building of larger TypeScript codebases. You can read more about composite projects [in the handbook](/docs/handbook/project-references.html). + +This option offers a way to configure the place where TypeScript keeps track of the files it stores on the disk to +indicate a project's build state — by default, they are in the same folder as your emitted JavaScript. diff --git a/packages/tsconfig-reference/copy/en/options/typeAcquisition.md b/packages/tsconfig-reference/copy/en/options/typeAcquisition.md index 428ee170a56b..da3d624a885f 100644 --- a/packages/tsconfig-reference/copy/en/options/typeAcquisition.md +++ b/packages/tsconfig-reference/copy/en/options/typeAcquisition.md @@ -2,4 +2,35 @@ display: "Type Acquisition" --- -TODO +When you have a JavaScript project in your editor, TypeScript will provide types for your `node_modules` automatically using the DefinitelyTyped set of `@types` definitions. +This is called automatic type acquisition, and you can customize it using the `typeAcquisition` object in your configuration. + +If you would like to disable or customize this feature, create a `jsconfig.json` in the root of your project: + +```json +{ + "typeAcquisition": { + "enable": false + } +} +``` + +If you have a specific module which should be included (but isn't in `node_modules`): + +```json +{ + "typeAcquisition": { + "include": ["jest"] + } +} +``` + +If a module should not be automatically acquired, for example if the library is available in your `node_modules` but your team has agreed to not use it: + +```json +{ + "typeAcquisition": { + "exclude": ["jquery"] + } +} +``` diff --git a/packages/tsconfig-reference/copy/en/options/typeRoots.md b/packages/tsconfig-reference/copy/en/options/typeRoots.md index 1609a6c66b16..bf7d5ede5874 100644 --- a/packages/tsconfig-reference/copy/en/options/typeRoots.md +++ b/packages/tsconfig-reference/copy/en/options/typeRoots.md @@ -2,4 +2,19 @@ display: "Type Roots" --- -List of folders to include type definitions from. +By default all *visible* "`@types`" packages are included in your compilation. +Packages in `node_modules/@types` of any enclosing folder are considered *visible*. +For example, that means packages within `./node_modules/@types/`, `../node_modules/@types/`, `../../node_modules/@types/`, and so on. + +If `typeRoots` is specified, *only* packages under `typeRoots` will be included. For example: + +```json +{ + "compilerOptions": { + "typeRoots" : ["./typings", "./vendor/types"] + } +} +``` + +This config file will include *all* packages under `./typings` and `./vendor/types`, and no packages from `./node_modules/@types`. +All paths are relative to the `tsconfig.json`. diff --git a/packages/tsconfig-reference/copy/en/options/types.md b/packages/tsconfig-reference/copy/en/options/types.md index 6fd01c111529..4d1b2be82547 100644 --- a/packages/tsconfig-reference/copy/en/options/types.md +++ b/packages/tsconfig-reference/copy/en/options/types.md @@ -2,4 +2,21 @@ display: "Types" --- -Type declaration files to be included in compilation. +By default all *visible* "`@types`" packages are included in your compilation. +Packages in `node_modules/@types` of any enclosing folder are considered *visible*. +For example, that means packages within `./node_modules/@types/`, `../node_modules/@types/`, `../../node_modules/@types/`, and so on. + +If `types` is specified, only packages listed will be included. For instance: + +```json +{ + "compilerOptions": { + "types" : ["node", "lodash", "express"] + } +} +``` + +This `tsconfig.json` file will *only* include `./node_modules/@types/node`, `./node_modules/@types/lodash` and `./node_modules/@types/express`. +Other packages under `node_modules/@types/*` will not be included. + +This feature differs from [`typeRoots`](#typeRoots) in that it is about specifying only the exact types you want included, whereas [`typeRoots`](#typeRoots) supports saying you want particular folders. diff --git a/packages/tsconfig-reference/copy/en/options/useDefineForClassFields.md b/packages/tsconfig-reference/copy/en/options/useDefineForClassFields.md index 788758751a9a..001fbca5819e 100644 --- a/packages/tsconfig-reference/copy/en/options/useDefineForClassFields.md +++ b/packages/tsconfig-reference/copy/en/options/useDefineForClassFields.md @@ -1,8 +1,9 @@ --- display: "Use Define For Class Fields" -introduced: "3.7" --- -This flag is used as a part of migrating to the upcoming standard version of how class fields works. TypeScript introduced class fields many years before it was ratified in TC39, where it had a different runtime behavior but the same syntax. This flag switches to the ECMA runtime behavior. +This flag is used as part of migrating to the upcoming standard version of class fields. TypeScript introduced class fields many years before it was ratified in TC39. The latest version of the upcoming specification has a different runtime behavior to TypeScript's implementation but the same syntax. -You can read more about the transition in [the 3.7 release notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#the-usedefineforclassfields-flag-and-the-declare-property-modifier). +This flag switches to the upcoming ECMA runtime behavior. + +You can read more about the transition in [the 3.7 release notes](/docs/handbook/release-notes/typescript-3-7.html#the-usedefineforclassfields-flag-and-the-declare-property-modifier). diff --git a/packages/tsconfig-reference/package.json b/packages/tsconfig-reference/package.json index ae61f60ec1f6..0dc4a7db62da 100644 --- a/packages/tsconfig-reference/package.json +++ b/packages/tsconfig-reference/package.json @@ -7,6 +7,7 @@ "generate-json": "yarn ts-node scripts/generateJSON.ts", "generate-markdown": "yarn ts-node --project tsconfig.json scripts/generateMarkdown.ts ", "build": "yarn generate-json; yarn generate-markdown", - "test": "echo 'no tests'" + "test": "yarn build; yarn lint", + "lint": "node scripts/lint.js" } } diff --git a/packages/tsconfig-reference/scripts/generateJSON.ts b/packages/tsconfig-reference/scripts/generateJSON.ts index 253dc37cd7f4..7455d57fc3ec 100644 --- a/packages/tsconfig-reference/scripts/generateJSON.ts +++ b/packages/tsconfig-reference/scripts/generateJSON.ts @@ -12,7 +12,16 @@ import { CommandLineOptionBase } from './types' import { writeFileSync } from 'fs' import { join } from 'path' import { format } from 'prettier' -import { denyList, relatedTo, deprecated, internal, defaultsForOptions, recommended, allowedValues, configToRelease } from './tsconfigRules' +import { + denyList, + relatedTo, + deprecated, + internal, + defaultsForOptions, + recommended, + allowedValues, + configToRelease, +} from './tsconfigRules' import { CompilerOptionName } from '../data/_types' const toJSONString = obj => format(JSON.stringify(obj, null, ' '), { filepath: 'thing.json' }) @@ -154,6 +163,16 @@ const topLevelTSConfigOptions: CompilerOptionJSON[] = [ }, defaultValue: 'false', }, + { + name: 'importHelpers', + type: 'string', + categoryCode: 6178, + // @ts-ignore + description: { + message: 'Print names of files part of the compilation.', + }, + defaultValue: 'false', + }, ] writeJSON('tsconfigOpts.json', { options: [...topLevelTSConfigOptions, ...filteredOptions] }) diff --git a/packages/tsconfig-reference/scripts/lint.js b/packages/tsconfig-reference/scripts/lint.js new file mode 100644 index 000000000000..1e71a9deda5b --- /dev/null +++ b/packages/tsconfig-reference/scripts/lint.js @@ -0,0 +1,33 @@ +// Loops through all the sample code and ensures that twoslash doesn't raise +const chalk = require("chalk") + +const tick = chalk.bold.greenBright("✓") + +const { readdirSync, readFileSync } = require('fs') +const { join } = require('path') + +const remark = require('remark') +const remarkTwoSlash = require('gatsby-remark-twoslasher-code-blocks') + +const languages = readdirSync(join(__dirname, '..', 'copy')).filter(f => !f.startsWith(".")) + +console.log("Linting the sample code which uses twoslasher in ts-config") + +// Pass in a 2nd arg to filter which markdown to run +const filterString = process.argv[2] ? process.argv[2] : "" + +languages.forEach(lang => { + const locale = join(__dirname, '..', 'copy', lang) + const options = readdirSync(join(locale, 'options')).filter(f => !f.startsWith(".")) + console.log("\n" + lang + ":") + + options.forEach(option => { + if (filterString.length && !option.includes(filterString)) return; + + const optionPath = join(locale, 'options', option) + const markdown = readFileSync(optionPath, "utf8") + const markdownAST = remark().parse(markdown) + remarkTwoSlash({ markdownAST }) + process.stdout.write(option + " " + tick + ", ") + }) +}) diff --git a/packages/tsconfig-reference/scripts/tsconfigRules.ts b/packages/tsconfig-reference/scripts/tsconfigRules.ts index 63d12d58b78b..7fd77794a25e 100644 --- a/packages/tsconfig-reference/scripts/tsconfigRules.ts +++ b/packages/tsconfig-reference/scripts/tsconfigRules.ts @@ -1,10 +1,10 @@ import { CompilerOptionName } from '../data/_types' /** Options which should never show on the references, basically anything that's for the CLI not the TSConfig */ -export const denyList: CompilerOptionName[] = ['help', 'init', 'all', 'watch', 'version', 'build', 'project'] +export const denyList: CompilerOptionName[] = ['help', 'init', 'all', 'watch', 'version', 'build', 'project', 'locale'] /** Things we should document, but really want to help move people away from */ -export const deprecated: CompilerOptionName[] = ['out', 'charset', 'keyofStringsOnly', 'moduleResolution', 'noErrorTruncation'] +export const deprecated: CompilerOptionName[] = ['out', 'charset', 'keyofStringsOnly', 'moduleResolution', 'noErrorTruncation', 'diagnostics'] /** Things which people really shouldn't use, but need to document */ export const internal: CompilerOptionName[] = ['preserveWatchOutput', 'stripInternal'] @@ -171,7 +171,7 @@ export const releaseToConfigsMap: { [key: string]: AnOption[] } = { '3.4': ['incremental', 'tsBuildInfoFile'], '3.2': ['strictBindCallApply', 'showConfig'], '3.0': ['composite', 'build'], - '2.9': ['keyofStringsOnly', 'noUnusedLocals', 'noUnusedParameters', 'declarationMap'], + '2.9': ['keyofStringsOnly', 'declarationMap'], '2.8': ['emitDeclarationOnly'], '2.7': ['strictPropertyInitialization', 'esModuleInterop'], '2.6': ['strictFunctionTypes'], diff --git a/packages/tsconfig-reference/tsconfig.json b/packages/tsconfig-reference/tsconfig.json index ca940d4b3864..840e16f861ad 100644 --- a/packages/tsconfig-reference/tsconfig.json +++ b/packages/tsconfig-reference/tsconfig.json @@ -1,7 +1,6 @@ { "compilerOptions": { "resolveJsonModule": true, - "checkJs": true, - "allowJs": true - } + "allowJs": true, + }, } diff --git a/packages/typescriptlang-org/_tests/backstop_data/bitmaps_reference/backstop_default_TSConfig_Example_0_viewport_0_phone.png b/packages/typescriptlang-org/_tests/backstop_data/bitmaps_reference/backstop_default_TSConfig_Example_0_viewport_0_phone.png index d50c35e2e0f4..577f741bb1f1 100644 Binary files a/packages/typescriptlang-org/_tests/backstop_data/bitmaps_reference/backstop_default_TSConfig_Example_0_viewport_0_phone.png and b/packages/typescriptlang-org/_tests/backstop_data/bitmaps_reference/backstop_default_TSConfig_Example_0_viewport_0_phone.png differ diff --git a/packages/typescriptlang-org/_tests/backstop_data/bitmaps_reference/backstop_default_TSConfig_Example_0_viewport_1_tablet.png b/packages/typescriptlang-org/_tests/backstop_data/bitmaps_reference/backstop_default_TSConfig_Example_0_viewport_1_tablet.png index 29af721aec68..8306b61f922d 100644 Binary files a/packages/typescriptlang-org/_tests/backstop_data/bitmaps_reference/backstop_default_TSConfig_Example_0_viewport_1_tablet.png and b/packages/typescriptlang-org/_tests/backstop_data/bitmaps_reference/backstop_default_TSConfig_Example_0_viewport_1_tablet.png differ diff --git a/packages/typescriptlang-org/_tests/backstop_data/bitmaps_reference/backstop_default_TSConfig_Example_0_viewport_2_computer.png b/packages/typescriptlang-org/_tests/backstop_data/bitmaps_reference/backstop_default_TSConfig_Example_0_viewport_2_computer.png index 832b8e7e6a7f..dc1d61d363fe 100644 Binary files a/packages/typescriptlang-org/_tests/backstop_data/bitmaps_reference/backstop_default_TSConfig_Example_0_viewport_2_computer.png and b/packages/typescriptlang-org/_tests/backstop_data/bitmaps_reference/backstop_default_TSConfig_Example_0_viewport_2_computer.png differ diff --git a/packages/typescriptlang-org/package.json b/packages/typescriptlang-org/package.json index f0c6282b556f..b888d18d20f0 100644 --- a/packages/typescriptlang-org/package.json +++ b/packages/typescriptlang-org/package.json @@ -7,6 +7,7 @@ "scripts": { "build": "gatsby build", "develop": "gatsby develop", + "clean": "gatsby clean", "update-snapshots": "backstop test; backstop approve", "start": "npm run develop", "serve": "gatsby serve",