- Advanced
- Allow Unreachable Code -
allowUnreachableCode
- Allow Unused Labels -
allowUnusedLabels
- Assume Changes Only Affect Direct Dependencies -
assumeChangesOnlyAffectDirectDependencies
- Charset -
charset
- Declaration Dir -
declarationDir
- Diagnostics -
diagnostics
- disableReferencedProjectLoad -
disableReferencedProjectLoad
- Disable Size Limit -
disableSizeLimit
- Disable Solution Searching -
disableSolutionSearching
- Disable Source Project Reference Redirect -
disableSourceOfProjectReferenceRedirect
- Emit BOM -
emitBOM
- Emit Declaration Only -
emitDeclarationOnly
- explainFiles -
explainFiles
- Extended Diagnostics -
extendedDiagnostics
- Force Consistent Casing In File Names -
forceConsistentCasingInFileNames
- Generate CPU Profile -
generateCpuProfile
- Imports Not Used As Values -
importsNotUsedAsValues
- JSX Factory -
jsxFactory
- jsxFragmentFactory -
jsxFragmentFactory
- jsxImportSource -
jsxImportSource
- Keyof Strings Only -
keyofStringsOnly
- List Emitted Files -
listEmittedFiles
- List Files -
listFiles
- Max Node Module JS Depth -
maxNodeModuleJsDepth
- New Line -
newLine
- No Emit Helpers -
noEmitHelpers
- No Emit On Error -
noEmitOnError
- No Error Truncation -
noErrorTruncation
- No Implicit Use Strict -
noImplicitUseStrict
- No Lib -
noLib
- No Resolve -
noResolve
- No Strict Generic Checks -
noStrictGenericChecks
- Out -
out
- Preserve Const Enums -
preserveConstEnums
- React Namespace -
reactNamespace
- Resolve JSON Module -
resolveJsonModule
- Skip Default Lib Check -
skipDefaultLibCheck
- Skip Lib Check -
skipLibCheck
- Strip Internal -
stripInternal
- Suppress Excess Property Errors -
suppressExcessPropertyErrors
- Suppress Implicit Any Index Errors -
suppressImplicitAnyIndexErrors
- Trace Resolution -
traceResolution
- Use Define For Class Fields -
useDefineForClassFields
- Allow Unreachable Code -
Advanced
Flags which help with debugging
Allow Unreachable Code - allowUnreachableCode
When:
undefined
(default) provide suggestions as warnings to editorstrue
unreachable code is ignoredfalse
raises compiler errors 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
:
Try
functionfn (n : number) {if (n > 5) {return true;} else {return false;}return true;Unreachable code detected.7027Unreachable code detected.}
This does not affect errors on the basis of code which appears to be unreachable due to type analysis.
Default:
undefined
Released:
Allow Unused Labels - allowUnusedLabels
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:
Try
functionverifyAge (age : number) {// Forgot 'return' statementif (age > 18) {Unused label.7028Unused label.verified: true;}}
Default:
false
Released:
Assume Changes Only Affect Direct Dependencies - assumeChangesOnlyAffectDirectDependencies
When this option is enabled, TypeScript will avoid rechecking/rebuilding all truly possibly-affected files, and only recheck/rebuild files that have changed as well as files that directly import them.
This can be considered a ‘fast & loose’ implementation of the watching algorithm, which can drastically reduce incremental rebuild times at the expense of having to run the full build occasionally to get all compiler error messages.
Released:
Charset - charset
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.
Status:
Deprecated
Default:
utf8
Declaration Dir - declarationDir
Offers a way to configure the root directory for where declaration files are emitted.
example
├── index.ts
├── package.json
└── tsconfig.json
with this tsconfig.json
:
{"": {"": true,"": "./types"}}
Would place the d.ts for the index.ts
in a types
folder:
example
├── index.js
├── index.ts
├── package.json
├── tsconfig.json
└── types
└── index.d.ts
Default:
n/a
Related:
Released:
Diagnostics - diagnostics
Used to output diagnostic information for debugging. This command is a subset of 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
instead.
Status:
Deprecated
Default:
false
Related:
disableReferencedProjectLoad - disableReferencedProjectLoad
In multi-project TypeScript programs, TypeScript will load all of the available projects into memory in order to provide accurate results for editor responses which require a full knowledge graph like ‘Find All References’.
If your project is large, you can use the flag disableReferencedProjectLoad
to disable the automatic loading of all projects. Instead, projects are loaded dynamically as you open files through your editor.
Released:
Disable Size Limit - disableSizeLimit
To avoid a possible memory bloat issues 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.
Default:
false
Disable Solution Searching - disableSolutionSearching
When working with composite TypeScript projects, this option provides a way to declare that you do not want a project to be included when using features like find all references or jump to definition in an editor.
This flag is something you can use to increase responsiveness in large composite projects.
Released:
Disable Source Project Reference Redirect - disableSourceOfProjectReferenceRedirect
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 of truth is now your TypeScript files.
Released:
Emit BOM - emitBOM
Controls whether TypeScript will emit a byte order mark (BOM) when writing output files. Some runtime environments require a BOM to correctly interpret a JavaScript files; others require that it is not present. The default value of false
is generally best unless you have a reason to change it.
Default:
false
Emit Declaration Only - emitDeclarationOnly
Only emit .d.ts
files; do not emit .js
files.
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.Default:
false
Related:
Released:
explainFiles - explainFiles
Print names of files which TypeScript sees as a part of your project and the reason they are part of the compilation.
For example, with this project of just a single index.ts
file
sh
example├── index.ts├── package.json└── tsconfig.json
Using a tsconfig.json
which has explainFiles
set to true:
json
{"compilerOptions": {"target": "es5","module": "commonjs","explainFiles": true}}
Running TypeScript against this folder would have output like this:
❯ tsc
node_modules/typescript/lib/lib.d.ts
Default library for target 'es5'
node_modules/typescript/lib/lib.es5.d.ts
Library referenced via 'es5' from file 'node_modules/typescript/lib/lib.d.ts'
node_modules/typescript/lib/lib.dom.d.ts
Library referenced via 'dom' from file 'node_modules/typescript/lib/lib.d.ts'
node_modules/typescript/lib/lib.webworker.importscripts.d.ts
Library referenced via 'webworker.importscripts' from file 'node_modules/typescript/lib/lib.d.ts'
node_modules/typescript/lib/lib.scripthost.d.ts
Library referenced via 'scripthost' from file 'node_modules/typescript/lib/lib.d.ts'
index.ts
Matched by include pattern '**/*' in 'tsconfig.json'
The output above show:
- The initial lib.d.ts lookup based on
target
, and the chain of.d.ts
files which are referenced - The
index.ts
file located via the default pattern ofinclude
This option is intended for debugging how a file has become a part of your compile.
Released:
Extended Diagnostics - extendedDiagnostics
You can use this flag to discover where TypeScript is spending it’s time when compiling. This is a tool used for understanding the performance characteristics of your codebase overall.
You can learn more about how to measure and understand the output in the performance section of the wiki.
Default:
false
Related:
Force Consistent Casing In File Names - forceConsistentCasingInFileNames
TypeScript follows the case sensitivity rules of the file system it’s running on. This can be problematic if some developers are working in a case-sensitive file system and others aren’t. If a file attempts to import fileManager.ts
by specifying ./FileManager.ts
the file will be found in a case-insensitive file system, but not on a case-sensitive file system.
When this option is set, TypeScript will issue an error if a program tries to include a file by a casing different from the casing on disk.
Recommended:
True
Default:
false
Generate CPU Profile - generateCpuProfile
This option gives you the chance to have TypeScript emit a v8 CPU profile during the compiler run. The CPU profile can provide insight into why your builds may be slow.
This option can only be used from the CLI via: --generateCpuProfile tsc-output.cpuprofile
.
sh
npm run tsc --generateCpuProfile tsc-output.cpuprofile
This file can be opened in a chromium based browser like Chrome or Edge Developer in the CPU profiler section. You can learn more about understanding the compilers performance in the TypeScript wiki section on performance.
Default:
profile.cpuprofile
Released:
Imports Not Used As Values - importsNotUsedAsValues
This flag controls how import
works, there are 3 different options:
remove
: The default behavior of droppingimport
statements which only reference types.preserve
: Preserves allimport
statements whose values or types are never used. This can cause imports/side-effects to be preserved.error
: This preserves all imports (the same as the preserve option), but will error when a value import is only used as a type. This might be useful if you want to ensure no values are being accidentally imported, but still make side-effect imports explicit.
This flag works because you can use import type
to explicitly create an import
statement which should never be emitted into JavaScript.
Allowed:
remove,
preserve,
errorReleased:
JSX Factory - jsxFactory
Changes the function called in .js
files when compiling JSX Elements using the classic JSX runtime. The most common change is to use "h"
or "preact.h"
instead of the default "React.createElement"
if using preact
.
For example, this TSX file:
tsx
import { h } from "preact";const HelloWorld = () => <div>Hello</div>;
With jsxFactory: "h"
looks like:
Try
"use strict";Object.defineProperty(exports, "__esModule", { value: true });const preact_1 = require("preact");const HelloWorld = () => preact_1.h("div", null, "Hello");
This option can be used on a per-file basis too similar to Babel’s /** @jsx h */
directive.
/** @jsx h */import {h } from "preact";Try
constHelloWorld = () => <div >Hello</div >;
The factory chosen will also affect where the JSX
namespace is looked up (for type checking information) before falling back to the global one.
If the factory is defined as React.createElement
(the default), the compiler will check for React.JSX
before checking for a global JSX
. If the factory is defined as h
, it will check for h.JSX
before a global JSX
.
Default:
React.createElement
Allowed:
Any identifier or dotted identifier
Related:
jsxFragmentFactory - jsxFragmentFactory
Specify the JSX fragment factory function to use when targeting react JSX emit with jsxFactory
compiler option is specified, e.g. Fragment
.
For example with this TSConfig:
{"": {"": "esnext","": "commonjs","": "react","": "h","": "Fragment"}}
This TSX file:
tsx
import { h, Fragment } from "preact";const HelloWorld = () => (<><div>Hello</div></>);
Would look like:
Try
"use strict";Object.defineProperty(exports, "__esModule", { value: true });const preact_1 = require("preact");const HelloWorld = () => (preact_1.h(preact_1.Fragment, null,preact_1.h("div", null, "Hello")));
This option can be used on a per-file basis too similar to Babel’s /* @jsxFrag h */
directive.
For example:
/** @jsx h *//** @jsxFrag Fragment */
import {h ,Fragment } from "preact";Try
constHelloWorld = () => (<><div >Hello</div ></>);
Related:
Released:
jsxImportSource - jsxImportSource
Declares the module specifier to be used for importing the jsx
and jsxs
factory functions when using jsx
as "react-jsx"
or "react-jsxdev"
which were introduced in TypeScript 4.1.
With React 17 the library supports a new form of JSX transformation via a separate import.
For example with this code:
tsx
import React from "react";function App() {return <h1>Hello World</h1>;}
Using this TSConfig:
{"": {"": "esnext","": "commonjs","": "react-jsx"}}
The emitted JavaScript from TypeScript is:
Try
"use strict";var __importDefault = (this && this.__importDefault) || function (mod) {return (mod && mod.__esModule) ? mod : { "default": mod };};Object.defineProperty(exports, "__esModule", { value: true });const jsx_runtime_1 = require("react/jsx-runtime");const react_1 = __importDefault(require("react"));function App() {return jsx_runtime_1.jsx("h1", { children: "Hello World" }, void 0);}
For example if you wanted to use "jsxImportSource": "preact"
, you need a tsconfig like:
{"": {"": "esnext","": "commonjs","": "react-jsx","": "preact","": ["preact"]}}
Which generates code like:
Try
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.App = void 0;const jsx_runtime_1 = require("preact/jsx-runtime");function App() {return jsx_runtime_1.jsx("h1", { children: "Hello World" }, void 0);}exports.App = App;
Alternatively, you can use a per-file pragma to set this option, for example:
tsx
/** @jsxImportSource preact */export function App() {return <h1>Hello World</h1>;}
Would add preact/jsx-runtime
as an import for the _jsx
factory.
Note: In order for this to work like you would expect, your tsx
file must include an export
or import
so that it is considered a module.
Default:
react
Related:
Released:
Keyof Strings Only - keyofStringsOnly
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.
Status:
Deprecated
Default:
false
Released:
List Emitted Files - listEmittedFiles
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.
For example:
example
├── index.ts
├── package.json
└── tsconfig.json
With:
{"": {"": true,"": 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.
Default:
false
List Files - listFiles
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:
{"": {"": 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
Note if using TypeScript 4.2, prefer explainFiles
which offers an explanation of why a file was added too.
Default:
false
Related:
Max Node Module JS Depth - maxNodeModuleJsDepth
The maximum dependency depth to search under node_modules
and load JavaScript files.
This flag is can only be used when 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.
Default:
0
New Line - newLine
Specify the end of line sequence to be used when emitting files: ‘CRLF’ (dos) or ‘LF’ (unix).
Default:
Platform specific
Released:
No Emit Helpers - noEmitHelpers
Instead of importing helpers with 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:
Try
constgetAPI = async (url : string) => {// Get APIreturn {};};
Which creates quite a lot of JavaScript:
Try
"use strict";var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }return new (P || (P = Promise))(function (resolve, reject) {function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }step((generator = generator.apply(thisArg, _arguments || [])).next());});};var __generator = (this && this.__generator) || function (thisArg, body) {var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;function verb(n) { return function (v) { return step([n, v]); }; }function step(op) {if (f) throw new TypeError("Generator is already executing.");while (_) try {if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;if (y = 0, t) op = [op[0] & 2, t.value];switch (op[0]) {case 0: case 1: t = op; break;case 4: _.label++; return { value: op[1], done: false };case 5: _.label++; y = op[1]; op = [0]; continue;case 7: op = _.ops.pop(); _.trys.pop(); continue;default:if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }if (t[2]) _.ops.pop();_.trys.pop(); continue;}op = body.call(thisArg, _);} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };}};var getAPI = function (url) { return __awaiter(void 0, void 0, void 0, function () {return __generator(this, function (_a) {// Get APIreturn [2 /*return*/, {}];});}); };
Which can be switched out with your own globals via this flag:
Try
"use strict";var getAPI = function (url) { return __awaiter(void 0, void 0, void 0, function () {return __generator(this, function (_a) {// Get APIreturn [2 /*return*/, {}];});}); };
Default:
false
Related:
Released:
No Emit On Error - noEmitOnError
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.
Default:
false
Released:
No Error Truncation - noErrorTruncation
Do not truncate error messages.
With false
, the default.
varx : {propertyWithAnExceedinglyLongName1 : string;propertyWithAnExceedinglyLongName2 : string;propertyWithAnExceedinglyLongName3 : string;propertyWithAnExceedinglyLongName4 : string;propertyWithAnExceedinglyLongName5 : string;};Try
// String representation of type of 'x' should be truncated in error messagevarType '{ propertyWithAnExceedinglyLongName1: string; propertyWithAnExceedinglyLongName2: string; propertyWithAnExceedinglyLongName3: string; propertyWithAnExceedinglyLongName4: string; propertyWithAnExceedinglyLongName5: string; }' is not assignable to type 'string'.: string = s ; x
Variable 'x' is used before being assigned.2322
2454Type '{ propertyWithAnExceedinglyLongName1: string; propertyWithAnExceedinglyLongName2: string; propertyWithAnExceedinglyLongName3: string; propertyWithAnExceedinglyLongName4: string; propertyWithAnExceedinglyLongName5: string; }' is not assignable to type 'string'.
Variable 'x' is used before being assigned.
With true
varx : {propertyWithAnExceedinglyLongName1 : string;propertyWithAnExceedinglyLongName2 : string;propertyWithAnExceedinglyLongName3 : string;propertyWithAnExceedinglyLongName4 : string;propertyWithAnExceedinglyLongName5 : string;};Try
// String representation of type of 'x' should be truncated in error messagevarType '{ propertyWithAnExceedinglyLongName1: string; propertyWithAnExceedinglyLongName2: string; propertyWithAnExceedinglyLongName3: string; propertyWithAnExceedinglyLongName4: string; propertyWithAnExceedinglyLongName5: string; }' is not assignable to type 'string'.: string = s ; x
Variable 'x' is used before being assigned.2322
2454Type '{ propertyWithAnExceedinglyLongName1: string; propertyWithAnExceedinglyLongName2: string; propertyWithAnExceedinglyLongName3: string; propertyWithAnExceedinglyLongName4: string; propertyWithAnExceedinglyLongName5: string; }' is not assignable to type 'string'.
Variable 'x' is used before being assigned.
Status:
Deprecated
Default:
false
No Implicit Use Strict - noImplicitUseStrict
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.
Try
define(["require", "exports"], function (require, exports) {exports.__esModule = true;exports.fn = void 0;function fn() { }exports.fn = fn;});
Try
define(["require", "exports"], function (require, exports) {"use strict";exports.__esModule = true;exports.fn = void 0;function fn() { }exports.fn = fn;});
Default:
false
No Lib - noLib
Disables the automatic inclusion of any library files. If this option is set, lib
is ignored.
Default:
false
Related:
No Resolve - noResolve
By default, TypeScript will examine the initial set of files for import
and <reference
directives and add these resolved files to your program.
If noResolve
is set, this process doesn’t happen. However, import
statements are still checked to see if they resolve to a valid module, so you’ll need to make sure this is satisfied by some other means.
Default:
false
No Strict Generic Checks - noStrictGenericChecks
TypeScript will unify type parameters when comparing two generic functions.
typeA = <T ,U >(x :T ,y :U ) => [T ,U ];typeB = <S >(x :S ,y :S ) => [S ,S ];
functionf (a :A ,b :B ) {b =a ; // OkType 'B' is not assignable to type 'A'.= a b ; // ErrorTypes of parameters 'y' and 'y' are incompatible.
Type 'U' is not assignable to type 'T'.
'T' could be instantiated with an arbitrary type which could be unrelated to 'U'.2322Type 'B' is not assignable to type 'A'.
Types of parameters 'y' and 'y' are incompatible.
Type 'U' is not assignable to type 'T'.
'T' could be instantiated with an arbitrary type which could be unrelated to 'U'.
Try}
This flag can be used to remove that check.
Default:
false
Released:
Out - out
Use 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 and is deprecated.
Preserve Const Enums - preserveConstEnums
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:
const enumAlbum {JimmyEatWorldFutures = 1,TubRingZooHypothesis = 2,DogFashionDiscoAdultery = 3,}Try
constselectedAlbum =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.
Try
"use strict";const selectedAlbum = 1 /* JimmyEatWorldFutures */;if (selectedAlbum === 1 /* JimmyEatWorldFutures */) {console.log("That is a great choice.");}
With preserveConstEnums
set to true
, the enum
exists at runtime and the numbers are still emitted.
Try
"use strict";var Album;(function (Album) {Album[Album["JimmyEatWorldFutures"] = 1] = "JimmyEatWorldFutures";Album[Album["TubRingZooHypothesis"] = 2] = "TubRingZooHypothesis";Album[Album["DogFashionDiscoAdultery"] = 3] = "DogFashionDiscoAdultery";})(Album || (Album = {}));const selectedAlbum = 1 /* JimmyEatWorldFutures */;if (selectedAlbum === 1 /* JimmyEatWorldFutures */) {console.log("That is a great choice.");}
This essentially makes such const enums
a source-code feature only, with no runtime traces.
Default:
false
React Namespace - reactNamespace
Use --jsxFactory
instead. Specify the object invoked for createElement
when targeting react
for TSX files.
Default:
"React"
Resolve JSON Module - resolveJsonModule
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:
// @filename: settings.jsonCannot find module './settings.json'. Consider using '--resolveJsonModule' to import module with '.json' extension.2732Cannot find module './settings.json'. Consider using '--resolveJsonModule' to import module with '.json' extension.{"repo": "TypeScript","dry": false,"debug": false}// @filename: index.tsimportsettings from "./settings.json";Try
settings .debug === true;settings .dry === 2;
Enabling the option allows importing JSON, and validating the types in that JSON file.
// @filename: settings.json{"repo": "TypeScript","dry": false,This condition will always return 'false' since the types 'boolean' and 'number' have no overlap.2367This condition will always return 'false' since the types 'boolean' and 'number' have no overlap."debug": false}// @filename: index.tsimportsettings from "./settings.json";Try
settings .debug === true;settings .dry === 2;
Default:
false
Skip Default Lib Check - skipDefaultLibCheck
Use --skipLibCheck
instead. Skip type checking of default library declaration files.
Default:
false
Skip Lib Check - skipLibCheck
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 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.
Recommended:
True
Default:
false
Released:
Strip Internal - stripInternal
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.
/*** Days available in a week* @internal*/export constdaysInAWeek = 7;Try
/** Calculate how much someone earns in a week */export functionweeklySalary (dayRate : number) {returndaysInAWeek *dayRate ;}
With the flag set to false
(default):
Try
/*** Days available in a week* @internal*/export declare const daysInAWeek = 7;/** Calculate how much someone earns in a week */export declare function weeklySalary(dayRate: number): number;
With stripInternal
set to true
the d.ts
emitted will be redacted.
Try
/** Calculate how much someone earns in a week */export declare function weeklySalary(dayRate: number): number;
The JavaScript output is still the same.
Status:
internal
Suppress Excess Property Errors - suppressExcessPropertyErrors
This disables reporting of excess property errors, such as the one shown in the following example:
typePoint = {x : number;y : number };constType '{ x: number; y: number; m: number; }' is not assignable to type 'Point'.p :Point = {x : 1,y : 3,m : 10 };Object literal may only specify known properties, and 'm' does not exist in type 'Point'.2322Type '{ x: number; y: number; m: number; }' is not assignable to type 'Point'.
Object literal may only specify known properties, and 'm' does not exist in type 'Point'.
Try
This flag was added to help people migrate to the stricter checking of new object literals in TypeScript 1.6.
We don’t recommend using this flag in a modern codebase, you can suppress one-off cases where you need it using // @ts-ignore
.
Default:
false
Suppress Implicit Any Index Errors - suppressImplicitAnyIndexErrors
Turning suppressImplicitAnyIndexErrors
on suppresses reporting the error about implicit anys when indexing into objects, as shown in the following example:
constobj = {x : 10 };Element implicitly has an 'any' type because expression of type '"foo"' can't be used to index type '{ x: number; }'.console .log (obj ["foo"]);Property 'foo' does not exist on type '{ x: number; }'.7053Element implicitly has an 'any' type because expression of type '"foo"' can't be used to index type '{ x: number; }'.
Property 'foo' does not exist on type '{ x: number; }'.
Try
Using suppressImplicitAnyIndexErrors
is quite a drastic approach. It is recommended to use a @ts-ignore
comment instead:
Try
constobj = {x : 10 };// @ts-ignoreconsole .log (obj ["foo"]);
Default:
false
Related:
Trace Resolution - traceResolution
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.
Default:
false
Released:
Use Define For Class Fields - useDefineForClassFields
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.
This flag switches to the upcoming ECMA runtime behavior.
You can read more about the transition in the 3.7 release notes.
Default:
false
Released: