Compiler Options

"compilerOptions"

Command Line
  1. preserveWatchOutput and
  2. pretty

Root Fields

Starting up are the root options in the TSConfig - these options relate to how your TypeScript or JavaScript project is set up.

# Files - files

프로그램에 포함할 파일 허용 목록을 지정합니다. 파일을 찾지 못하면 오류가 발생합니다.

{
"": [
"core.ts",
"sys.ts",
"types.ts",
"scanner.ts",
"parser.ts",
"utilities.ts",
"binder.ts",
"checker.ts",
"tsc.ts"
]
}

파일 수가 적어 파일 참조에 glob을 사용할 필요가 없을 때 유용합니다. 필요한 경우 include을 사용합니다.

# Extends - extends

The value of extends is a string which contains a path to another configuration file to inherit from. The path may use Node.js style resolution.

The configuration from the base file are loaded first, then overridden by those in the inheriting config file. All relative paths found in the configuration file will be resolved relative to the configuration file they originated in.

It’s worth noting that files, include and exclude from the inheriting config file overwrite those from the base config file, and that circularity between configuration files is not allowed.

Currently, the only top-level property that is excluded from inheritance is references.

Example

configs/base.json:

tsconfig.json:

{
"": "./configs/base",
"": ["main.ts", "supplemental.ts"]
}

tsconfig.nostrictnull.json:

{
"": "./tsconfig",
}
}

Properties with relative paths found in the configuration file, which aren’t excluded from inheritance, will be resolved relative to the configuration file they originated in.

  • Default:

    false

  • Released:

    2.1

# Include - include

프로그램에 포함할 파일 이름이나 패턴을 배열로 지정합니다. 이 파일 이름은 tsconfig.json 파일에 포함된 디렉터리를 기준으로 하여 결정됩니다.

json
{
"include": ["src/**/*", "tests/**/*"]
}

위 문법은 아래와 같이 파일을 포함합니다.

. ├── 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

includeexclude는 글롭(glob) 패턴을 만들기 위한 와일드카드 문자를 지원합니다.:

  • * 0개 혹은 그 이상의 문자를 매치합니다. (디렉터리 구분자를 제외하고)
  • ? 문자 한 개를 매치합니다. (디렉터리 구분자를 제외하고)
  • **/ 모든 하위 디렉터리를 매치합니다.

만약 글롭 패턴에 파일 확장자가 포함되어있지 않다면 오직 지원되는 확장자를 가진 파일들만 포함됩니다. (e. g. .ts, .tsx, .d.ts가 기본적으로 포함되며, allowJS가 true로 설정되었을 경우에는 .js, .jsx 까지 포함)

  • Default:

    [] if files is specified, otherwise ["**/*"]

  • Related:

    files, exclude

  • Released:

    2.0

# Exclude - exclude

include 에서 파일을 포함할 때 생략할 파일 이름이나 패턴을 배열로 지정합니다.

중요 : exclude오직 include 의 설정의 결과로 포함되는 파일만 변경합니다. exclude 로 지정된 파일은 코드상의 types를 포함하여, import에 의해 코드 베이스의 일부가 될 수 있습니다. 이는 /// <reference 지시문 또는 files 목록에 지정되어 있기 때문입니다.

이것은 파일이 코드 베이스에 포함되는 것을 방지하는 메커니즘이 아닙니다. 단순히 include의 설정이 찾은 내용만을 변경하게 됩니다.

  • Default:

    ["node_modules", "bower_components", "jspm_packages"], plus the value of outDir if one is specified.

  • Related:

    include, files

# References - references

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 section of the handbook

  • Default:

    false

Compiler Options

These options make up the bulk of TypeScript’s configuration and it covers how the language should work.

#Project Options

이 설정은 프로젝트의 런타임 예상 동작, JavaScript 파일을 내보낼 위치나 방법 그리고 기존 JavaScript 코드가 통합되는 수준을 정의하는데 사용됩니다.

# Allow JS - allowJs

Allow JavaScript files to be imported inside your project, instead of just .ts and .tsx files. For example, this JS file:

// @filename: card.js
export const defaultCardDeck = "Heart";
Try

When imported into a TypeScript file will raise an error:

// @filename: index.ts
import { defaultCardDeck } from "./card";
console.log(defaultCardDeck);
Try

Imports fine with allowJs enabled:

// @filename: index.ts
import { defaultCardDeck } from "./card";
console.log(defaultCardDeck);
Try

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.

# Check JS - checkJs

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:

// @filename: constants.js
module.exports.pi = parseFloat(3.124);
// @filename: index.ts
import { pi } from "./constants";
console.log(pi);
Try

You will not get any errors. However, if you turn on checkJs then you will get error messages from the JavaScript file.

// @filename: constants.js
Argument of type 'number' is not assignable to parameter of type 'string'.2345Argument of type 'number' is not assignable to parameter of type 'string'.
module.exports.pi = parseFloat(3.124);
// @filename: index.ts
import { pi } from "./constants";
console.log(pi);
Try

# Composite - composite

composite 옵션은 아직 빌드되지 않은 프로젝트의 빠른 빌드 설정을 위해 빌드 도구(—build 모드에서 TypeScript를 포함한)에 특정 조건을 적용합니다.

이 설정이 켜져 있으면:

  • 만약 rootDir 설정이 설정되어 있지 않다면, 기본값은 ‘tsconfig.json’ 파일을 포함하는 디렉터리입니다.
  • 모든 실행 파일은 include 패턴과 일치하거나 파일 배열에 나열되어야 합니다. 만약 이 제약 조건을 위반하면, ‘tsc’는 지정되지 않은 파일을 알려줍니다.
  • declaration의 기본값은 true 입니다.

TypeScript 프로젝트에 대한 문서는 핸드북에서 확인할 수 있습니다.

# Declaration - declaration

프로젝트 내의 모든 TypeScript나 JavaScript 파일에 대한 .d.ts파일을 생성합니다. 이러한 .d.ts파일은 모듈의 외부 API를 설명하는 타입 정의 파일입니다. .d.ts 파일 사용하면, TypeScript와 같은 도구로 intellisense와 타입이 정해지지 않은 코드의 정확한 타입을 제공할 수 있습니다.

declarationtrue로 설정되면, 아래와 같은 TypeScript 코드로 컴파일러를 실행합니다:

export let helloWorld = "hi";
Try

아래와 같은index.js파일이 생성될 것입니다:

export let helloWorld = "hi";
Try

해당 helloWorld.d.ts:

export declare let helloWorld: string;
Try

JavaScript 파일 용 .d.ts파일로 작업할 때, emitDeclarationOnly를 사용하거나 outDir를 사용하여 JavaScript 파일이 덮어써지지 않도록 할 수 있습니다.

# Declaration Map - declarationMap

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.

  • Default:

    false

  • Released:

    2.9

# Downlevel Iteration - downlevelIteration

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.

Example: Effects on for / of

With this TypeScript code:

const str = "Hello!";
for (const s of str) {
console.log(s);
}
Try

Without downlevelIteration enabled, a for / of loop on any object is downleveled to a traditional for loop:

"use strict";
var str = "Hello!";
for (var _i = 0, str_1 = str; _i < str_1.length; _i++) {
var s = str_1[_i];
console.log(s);
}
Try

This is often what people expect, but it’s not 100% compliant with ECMAScript iteration protocol. Certain strings, such as emoji (😜), have a .length of 2 (or even more!), but should iterate as 1 unit in a for-of loop. See this blog post by Jonathan New for a longer explanation.

When downlevelIteration is enabled, TypeScript will use a helper function that checks for a Symbol.iterator implementation (either native or polyfill). If this implementation is missing, you’ll fall back to index-based iteration.

"use strict";
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var e_1, _a;
var str = "Hello!";
try {
for (var str_1 = __values(str), str_1_1 = str_1.next(); !str_1_1.done; str_1_1 = str_1.next()) {
var s = str_1_1.value;
console.log(s);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (str_1_1 && !str_1_1.done && (_a = str_1.return)) _a.call(str_1);
}
finally { if (e_1) throw e_1.error; }
}
Try

You can use tslib via importHelpers to reduce the amount of inline JavaScript too:

"use strict";
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var e_1, _a;
var str = "Hello!";
try {
for (var str_1 = __values(str), str_1_1 = str_1.next(); !str_1_1.done; str_1_1 = str_1.next()) {
var s = str_1_1.value;
console.log(s);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (str_1_1 && !str_1_1.done && (_a = str_1.return)) _a.call(str_1);
}
finally { if (e_1) throw e_1.error; }
}
Try

Note: enabling downlevelIteration does not improve compliance if Symbol.iterator is not present in the runtime.

Example: Effects on Array Spreads

This is an array spread:

js
// Make a new array who elements are 1 followed by the elements of arr2
const arr = [1, ...arr2];

Based on the description, it sounds easy to downlevel to ES5:

js
// The same, right?
const arr = [1].concat(arr2);

However, this is observably different in certain rare cases. For example, if an array has a “hole” in it, the missing index will create an own property if spreaded, but will not if built using concat:

js
// Make an array where the '1' element is missing
let missing = [0, , 1];
let spreaded = [...missing];
let concated = [].concat(missing);
// true
"1" in spreaded;
// false
"1" in concated;

Just as with for / of, downlevelIteration will use Symbol.iterator (if present) to more accurately emulate ES 6 behavior.

# Import Helpers - importHelpers

For certain downleveling operations, TypeScript uses some helper code for operations like extending class, spreading arrays or objects, and async operations. By default, these helpers are inserted into files which use them. This can result in code duplication if the same helper is used in many different modules.

If the importHelpers flag is on, these helper functions are instead imported from the tslib module. You will need to ensure that the tslib module is able to be imported at runtime. This only affects modules; global script files will not attempt to import modules.

For example, with this TypeScript:

ts
export function fn(arr: number[]) {
const arr2 = [1, ...arr];
}

Turning on downlevelIteration and importHelpers is still false:

var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
export function fn(arr) {
var arr2 = __spreadArray([1], __read(arr));
}
Try

Then turning on both downlevelIteration and importHelpers:

import { __read, __spreadArray } from "tslib";
export function fn(arr) {
var arr2 = __spreadArray([1], __read(arr));
}
Try

You can use noEmitHelpers when you provide your own implementations of these functions.

# Incremental - incremental

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.

To control which folders you want to the files to be built to, use the config option tsBuildInfoFile.

# Isolated Modules - isolatedModules

While you can use TypeScript to produce JavaScript code from TypeScript code, it’s also common to use other transpilers such as Babel to do this. However, other transpilers only operate on a single file at a time, which means they can’t apply code transforms that depend on understanding the full type system. This restriction also applies to TypeScript’s ts.transpileModule API which is used by some build tools.

These limitations can cause runtime problems with some TypeScript features like const enums and namespaces. Setting the isolatedModules flag tells TypeScript to warn you if you write certain code that can’t be correctly interpreted by a single-file transpilation process.

It does not change the behavior of your code, or otherwise change the behavior of TypeScript’s checking and emitting process.

Some examples of code which does not work when isolatedModules is enabled.

Exports of Non-Value Identifiers

In TypeScript, you can import a type and then subsequently export it:

import { someType, someFunction } from "someModule";
someFunction();
export { someType, someFunction };
Try

Because there’s no value for someType, the emitted export will not try to export it (this would be a runtime error in JavaScript):

js
export { someFunction };

Single-file transpilers don’t know whether someType produces a value or not, so it’s an error to export a name that only refers to a type.

Non-Module Files

If isolatedModules is set, all implementation files must be modules (which means it has some form of import/export). An error occurs if any file isn’t a module:

function fn() {}
'index.ts' cannot be compiled under '--isolatedModules' because it is considered a global script file. Add an import, export, or an empty 'export {}' statement to make it a module.1208'index.ts' cannot be compiled under '--isolatedModules' because it is considered a global script file. Add an import, export, or an empty 'export {}' statement to make it a module.
Try

This restriction doesn’t apply to .d.ts files.

References to const enum members

In TypeScript, when you reference a const enum member, the reference is replaced by its actual value in the emitted JavaScript. Changing this TypeScript:

declare const enum Numbers {
Zero = 0,
One = 1,
}
console.log(Numbers.Zero + Numbers.One);
Try

To this JavaScript:

"use strict";
console.log(0 + 1);
Try

Without knowledge of the values of these members, other transpilers can’t replace the references to Numbers, which would be a runtime error if left alone (since there are no Numbers object at runtime). Because of this, when isolatedModules is set, it is an error to reference an ambient const enum member.

  • Default:

    false

# JSX - jsx

Controls how JSX constructs are emitted in JavaScript files. This only affects output of JS files that started in .tsx files.

  • react: Emit .js files with JSX changed to the equivalent React.createElement calls
  • react-jsx: Emit .js files with the JSX changed to _jsx calls
  • react-jsxdev: Emit .js files with the JSX to _jsx calls
  • preserve: Emit .jsx files with the JSX unchanged
  • react-native: Emit .js files with the JSX unchanged

For example

This sample code:

tsx
export const helloWorld = () => <h1>Hello world</h1>;

Default: "react"

export const helloWorld = () => React.createElement("h1", null, "Hello world");
Try

Preserve: "preserve"

export const helloWorld = () => <h1>Hello world</h1>;
Try

React Native: "react-native"

export const helloWorld = () => <h1>Hello world</h1>;
Try

React 17 transform: "react-jsx"[1]

import { jsx as _jsx } from "react/jsx-runtime";
export const helloWorld = () => _jsx("h1", { children: "Hello world" }, void 0);
Try

React 17 dev transform: "react-jsxdev"[1]

import { jsxDEV as _jsxDEV } from "react/jsx-dev-runtime";
const _jsxFileName = "/home/runner/work/TypeScript-Website/TypeScript-Website/packages/typescriptlang-org/index.tsx";
export const helloWorld = () => _jsxDEV("h1", { children: "Hello world" }, void 0, false, { fileName: _jsxFileName, lineNumber: 7, columnNumber: 32 }, this);
Try

# Lib - lib

TypeScript는 JS API(Math 와 같은)에 대한 기본적인 타입 정의와 브라우저 환경(document 와 같은)에 있는 타입 정의를 포함합니다. 이 뿐만 아니라 TypeScript는 지정한 target 과 일치하는 최신 JS 기능을 위한 API도 포함되어 있습니다; 예를 들어 targetES6 이상이면 Map 에 대한 정의를 사용할 수 있습니다.

이는 몇 가지 이유에 의해 변경될 수 있습니다:

  • 프로그램이 브라우저에서 동작하지 않아 "dom" 타입의 정의가 필요 없을 경우
  • 런타임 플랫폼이 특정 JavaScript API 객체를 제공하지만(폴리필을 통해서) 아직 주어진 ECMAScript 버전의 문법을 일부 지원하지 않을 경우
  • 더 높은 버전의 ECMAScript을 위한 폴리필이나 네이티브 구현이 있을 경우

상위 레벨 라이브러리

Name Contents
ES5 모든 ES3 및 ES5 기능에 대한 핵심적인 정의
ES2015 ES2015(또는 ES6로 알려진)에서 추가로 사용 가능한 API - array.find, Promise, Proxy, Symbol, Map, Set, Reflect, 기타 등등
ES6 “ES2015” 의 별칭
ES2016 ES2016에서 추가로 사용 가능한 API - array.include, 기타 등등
ES7 “ES2016” 의 별칭
ES2017 ES2017 에서 추가로 사용 가능한 API - Object.entries, Object.values, Atomics, SharedArrayBuffer, date.formatToParts, typed arrays, 기타 등등
ES2018 ES2018 에서 추가로 사용 가능한 API - async iterables, promise.finally, Intl.PluralRules, rexexp.groups, 기타 등등
ES2019 ES2019 에서 추가로 사용 가능한 API - array.flat, array.flatMap, Object.fromEntries, string.trimStart, string.trimEnd, 기타 등등
ES2020 ES2020 에서 추가로 사용 가능한 API - string.matchAll, etc.
ESNext ESNext 에서 추가로 사용 가능한 API - 이는 JavaScript의 사양이 향상될 때 마다 변함.
DOM DOM 정의 - window, document, etc.
WebWorker 웹 워커(WebWorker) 환경에서 추가로 사용 가능한 API
ScriptHost 윈도우 스크립트 호스트 시스템(Windows Script Hosting System) 을 위한 API

개별적인 라이브러리 컴포넌트

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

위 목록들은 최신이 아닐수도 있습니다. 전체적인 목록은 TypeScript의 소스 코드 에서 조회할 수 있습니다.

  • Allowed:

    See main content

  • Related:

    noLib

  • Released:

    2.0

# Module - module

Sets the module system for the program. See the Modules reference page for more information. You very likely want "CommonJS" for node projects.

Changing module affects moduleResolution which also has a reference page.

Here’s some example output for this file:

// @filename: index.ts
import { valueOfPi } from "./constants";
export const twoPi = valueOfPi * 2;
Try

CommonJS

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.twoPi = void 0;
const constants_1 = require("./constants");
exports.twoPi = constants_1.valueOfPi * 2;
Try

UMD

(function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports", "./constants"], factory);
}
})(function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.twoPi = void 0;
const constants_1 = require("./constants");
exports.twoPi = constants_1.valueOfPi * 2;
});
Try

AMD

define(["require", "exports", "./constants"], function (require, exports, constants_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.twoPi = void 0;
exports.twoPi = constants_1.valueOfPi * 2;
});
Try

System

System.register(["./constants"], function (exports_1, context_1) {
"use strict";
var constants_1, twoPi;
var __moduleName = context_1 && context_1.id;
return {
setters: [
function (constants_1_1) {
constants_1 = constants_1_1;
}
],
execute: function () {
exports_1("twoPi", twoPi = constants_1.valueOfPi * 2);
}
};
});
Try

ESNext

import { valueOfPi } from "./constants";
export const twoPi = valueOfPi * 2;
Try

ES2020

import { valueOfPi } from "./constants";
export const twoPi = valueOfPi * 2;
Try

ES6

import { valueOfPi } from "./constants";
export const twoPi = valueOfPi * 2;
Try

If you are wondering about the difference between ES2015 and ES2020, ES2020 adds support for dynamic imports, and import.meta.

None

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.twoPi = void 0;
const constants_1 = require("./constants");
exports.twoPi = constants_1.valueOfPi * 2;
Try
  • Allowed:

    CommonJS (default if target is ES3 or ES5),
    ,
    ES6,
    ES2015,
    ES2020,
    ,
    None,
    UMD,
    AMD,
    System,
    ESNext

  • Related:

    moduleResolution

  • Released:

    1.0

# No Emit - noEmit

Do not emit compiler output files like JavaScript source code, source-maps or declarations.

This makes room for another tool like Babel, or 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.

  • Default:

    false

# Out Dir - outDir

만일 지정하면, .js (이 외에도 .d.ts, .js.map, 등.) 파일이 지정한 디렉터리로 배출됩니다. 원본 파일의 디렉터리 구조는 보존됩니다; 계산된 루트가 예상과 다를 경우 rootDir 을 보세요.

만일 지정하지 않으면, .js 파일은 .ts 파일이 생성된 곳과 동일한 디렉터리에 생성됩니다:

sh
$ tsc
example
├── index.js
└── index.ts

다음과 같이 tsconfig.json 을 작성할 경우:

{
"": "dist"
}
}

이러한 설정으로 tsc를 실행하면 파일이 지정한 dist 폴더로 이동합니다:

sh
$ tsc
example
├── dist
│ └── index.js
├── index.ts
└── tsconfig.json

# Out File - outFile

만일 지정하면, 모든 전역 (비모듈) 파일이 지정된 단일 출력 파일에 연결됩니다.

만일 modulesystem 또는 amd 일 경우, 모든 모듈 파일도 모든 전역 컨텐츠 뒤에 이 파일에 연결됩니다.

참고: outFilemoduleNone 이거나, System, AMD 가 아니면 사용할 수 없습니다. 이 옵션은 bundle CommonJS 또는 ES6 모듈에 사용할 수 없습니다.

# Plugins - plugins

에디터 내에서 실행할 언어 서비스 플러그인 목록.

언어 서비스 플러그인은 기존 TypeScript 파일을 기반으로 사용자에게 추가 정보를 제공하는 방법입니다. TypeScript와 편집자 간의 기존 메시지를 개선하거나 자체 오류 메시지를 제공할 수 있습니다.

예를 들면:

VS Code는 automatically include language service plugins에 대한 확장 기능이 있어서, tsconfig.json에서 정의 할 필요 없이 에디터에서 일부를 실행할 수 있습니다.

    # Remove Comments - removeComments

    Strips all comments from TypeScript files when converting into JavaScript. Defaults to false.

    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";

    When removeComments is set to true:

    export const helloWorldPTBR = "Olá Mundo";
    Try

    Without setting removeComments or having it as false:

    /** The translation of 'Hello world' into Portuguese */
    export const helloWorldPTBR = "Olá Mundo";
    Try

    This means that your comments will show up in the JavaScript code.

    • Default:

      false

    # Root Dir - rootDir

    Default: The longest common path of all non-declaration input files. If composite is set, the default is instead the directory containing the tsconfig.json file.

    When TypeScript compiles files, it keeps the same directory structure in the output directory as exists in the input directory.

    For example, let’s say you have some input files:

    MyProj ├── tsconfig.json ├── core │ ├── a.ts │ ├── b.ts │ ├── sub │ │ ├── c.ts ├── types.d.ts

    The inferred value for rootDir is the longest common path of all non-declaration input files, which in this case is core/.

    If your outDir was dist, TypeScript would write this tree:

    MyProj ├── dist │ ├── a.js │ ├── b.js │ ├── sub │ │ ├── c.js

    However, you may have intended for core to be part of the output directory structure. By setting rootDir: "." in tsconfig.json, TypeScript would write this tree:

    MyProj ├── dist │ ├── core │ │ ├── a.js │ │ ├── b.js │ │ ├── sub │ │ │ ├── c.js

    Importantly, rootDir does not affect which files become part of the compilation. It has no interaction with the include, exclude, or files tsconfig.json settings.

    Note that TypeScript will never write an output file to a directory outside of outDir, and will never skip emitting a file. For this reason, rootDir also enforces that all files which need to be emitted are underneath the rootDir path.

    For example, let’s say you had this tree:

    MyProj ├── tsconfig.json ├── core │ ├── a.ts │ ├── b.ts ├── helpers.ts

    It would be an error to specify rootDir as core and include as * because it creates a file (helpers.ts) that would need to be emitted outside the outDir (i.e. ../helpers.js).

    • Default:

      Computed from the list of input files

    • Released:

      1.5

    # Source Map - sourceMap

    Enables the generation of sourcemap files. 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 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
    // 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"
    }
    • Default:

      false

    # Target - target

    최신 브라우저는 모든 ES6 기능을 지원하므로 ES6는 좋은 선택입니다. 만약 코드가 이전 환경에서 배포된 경우라면 더 낮은 버전을, 최신 환경에서 실행이 보장되는 경우 더 높은 버전을 선택할 수 있습니다.

    target 설정은 하향 평준화된 JS 기능과 온전히 남아있는 것을 변경합니다. 예를 들어 target이 ES5 이하인 경우, 화살 함수 () => this는 동등한 function 표현식으로 바뀝니다.

    target을 바꾼다는 것은 마찬가지로 lib의 기본값을 바꿉니다. 원하는 대로 targetlib 설정을 “믹스 앤 매치” 할 수 있지만, 편의를 위해 target만 설정할 수 있습니다.

    Node와 같은 개발자 플랫폼의 경우 버전에 따라 대상에 대한 특정 기준이 있습니다. tsconfig/bases에서 공통 플랫폼 및 해당 버전에 대한 커뮤니티 구성 TSConfig 세트를 찾을 수 있습니다.

    ESNext 값은 특별하게 TypeScript가 지원하는 가장 높은 버전을 나타냅니다. 이 설정은 TypeScript 버전과 같다는 것을 의미하는 것이 아니며 업그레이드 예측 가능성을 낮출 수 있으므로 주의해야 합니다.

    • Default:

      ES3

    • Allowed:

      ES3 (default),
      ES5,
      ES6/ES2015 (synonymous),
      ES7/ES2016,
      ES2017,
      ES2018,
      ES2019,
      ES2020,
      ESNext

    • Released:

      1.0

    # TS Build Info File - tsBuildInfoFile

    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.

    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.

    #Strict Checks

    컴파일러 옵션 strict를 사용해 빌드 시 가능한 모든 개선점을 옵트-인하는 걸 추천합니다.

    TypeScript는 광범위한 JavaScript 패턴과 기본 값을 지원해 이런 스타일을 수용하는 상당한 유연성을 가집니다. 종종 코드베이스의 안전성과 잠재적 확장성은 이런 기술 중 일부와 상충 될 수 있습니다.

    다양한 JavaScript 버전을 지원하기 때문에, TypeScript를 새 버전으로 업데이트하면 두 가지 유형의 오류를 발견할 수 있습니다.

    • TypeScript가 JavaScript의 이해도를 개선해 발견한 코드베이스에 이미 존재했던 오류들.
    • 새로운 문제 영역을 다루는 새로운 오류 모음.

    일반적으로 TypeScript는 후자의 오류 집합에 대한 컴파일러 플래그를 추가하며, 기본적으로 비활성화됩니다.

    # Always Strict - alwaysStrict

    파일을 ECMAScript 엄격 모드로 분석 하고, 각 소스 파일에 “use strict”를 생성합니다.

    ES5에 도입된 ECMAScript 엄격 모드는 성능 향상을 위해 JavaScript 엔진의 런타임 동작을 변화시켜, 일련의 에러를 무시하지 않고 발생시킵니다.

    • Recommended:

      True

    • Default:

      false, unless strict is set

    • Related:

      strict

    • Released:

      2.1

    # No Implicit Any - noImplicitAny

    타입이 표기되어 있지 않아, 타입 추론을 할 수 없을 때 TypeScript는 해당 변수의 타입을 any로 대체합니다.

    이것으로 인해 일부 오류가 누락될 수 있습니다. 예를 들면:

    function fn(s) {
    // 오류가 아닌가요?
    console.log(s.subtr(3));
    }
    fn(42);
    Try

    그러나 noImplicitAny를 활성화하면 TypeScript는 any를 추론 할 때마다 오류를 발생시킵니다:

    function fn(s) {
    Parameter 's' implicitly has an 'any' type.7006Parameter 's' implicitly has an 'any' type.
    console.log(s.subtr(3));
    }
    Try
    • Recommended:

      True

    • Default:

      false, unless strict is set

    • Related:

      strict

    # No Implicit This - noImplicitThis

    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.

    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;
    'this' implicitly has type 'any' because it does not have a type annotation.
    'this' implicitly has type 'any' because it does not have a type annotation.
    2683
    2683
    'this' implicitly has type 'any' because it does not have a type annotation.
    'this' implicitly has type 'any' because it does not have a type annotation.
    };
    }
    }
    Try
    • Recommended:

      True

    • Default:

      false, unless strict is set

    • Related:

      strict

    • Released:

      2.0

    # Strict - strict

    strict 플래그는 다양한 타입 검사를 가능하게 하여 프로그램 정확성을 더욱 보장합니다. strict 플래그를 켜는 것은 아래에 설명된 모든 strict mode family 옵션을 활성화하는 것과 같습니다. 필요에 따라 개별 strict mode family 검사를 끌 수 있습니다.

    향후 버전의 TypeScript는 이 플래그에서 추가적인 엄격한 검사를 도입할 수 있어, TypeScript를 업그레이드하면 프로그램에 새로운 타입 오류가 발생할 수도 있습니다. 적당히 가능할 때, 해당 플래그를 추가하여 동작을 비활성화합니다.

    # Strict Bind Call Apply - strictBindCallApply

    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:

    // With strictBindCallApply on
    function fn(x: string) {
    return parseInt(x);
    }
    const n1 = fn.call(undefined, "10");
    const n2 = fn.call(undefined, false);
    Argument of type 'boolean' is not assignable to parameter of type 'string'.2345Argument of type 'boolean' is not assignable to parameter of type 'string'.
    Try

    Otherwise, these functions accept any arguments and will return any:

    // With strictBindCallApply off
    function fn(x: string) {
    return parseInt(x);
    }
    // Note: No error; return type is 'any'
    const n = fn.call(undefined, false);
    Try
    • Recommended:

      True

    • Default:

      false, unless strict is set

    • Related:

      strict

    • Released:

      3.2

    # Strict Function Types - strictFunctionTypes

    When enabled, this flag causes functions parameters to be checked more correctly.

    Here’s a basic example with strictFunctionTypes off:

    function fn(x: string) {
    console.log("Hello, " + x.toLowerCase());
    }
    type StringOrNumberFunc = (ns: string | number) => void;
    // Unsafe assignment
    let func: StringOrNumberFunc = fn;
    // Unsafe call - will crash
    func(10);
    Try

    With strictFunctionTypes on, the error is correctly detected:

    function fn(x: string) {
    console.log("Hello, " + x.toLowerCase());
    }
    type StringOrNumberFunc = (ns: string | number) => void;
    // Unsafe assignment is prevented
    let func: StringOrNumberFunc = fn;
    Type '(x: string) => void' is not assignable to type 'StringOrNumberFunc'. Types of parameters 'x' and 'ns' are incompatible. Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'.2322Type '(x: string) => void' is not assignable to type 'StringOrNumberFunc'. Types of parameters 'x' and 'ns' are incompatible. Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'.
    Try

    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:

    type Methodish = {
    func(x: string | number): void;
    };
    function fn(x: string) {
    console.log("Hello, " + x.toLowerCase());
    }
    // Ultimately an unsafe assignment, but not detected
    const m: Methodish = {
    func: fn,
    };
    m.func(10);
    Try
    • Recommended:

      True

    • Default:

      false, unless strict is set

    • Related:

      strict

    • Released:

      2.6

    # Strict Null Checks - strictNullChecks

    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:

    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);
    Try

    Setting strictNullChecks to true will raise an error that you have not made a guarantee that the loggedInUser exists before trying to use it.

    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);
    Object is possibly 'undefined'.2532Object is possibly 'undefined'.
    Try

    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;
    };
    • Recommended:

      True

    • Default:

      false, unless strict is set

    • Related:

      strict

    • Released:

      2.0

    # Strict Property Initialization - strictPropertyInitialization

    When set to true, TypeScript will raise an error when a class property was declared but not set in the constructor.

    class UserAccount {
    name: string;
    accountType = "user";
    email: string;
    Property 'email' has no initializer and is not definitely assigned in the constructor.2564Property 'email' has no initializer and is not definitely assigned in the constructor.
    address: string | undefined;
    constructor(name: string) {
    this.name = name;
    // Note that this.email is not set
    }
    }
    Try

    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.
    • Recommended:

      True

    • Default:

      false, unless strict is set

    • Related:

      strict

    • Released:

      2.7

    #Module Resolution

    # Allow Synthetic Default Imports - allowSyntheticDefaultImports

    When set to true, allowSyntheticDefaultImports allows you to write an import like:

    ts
    import React from "react";

    instead of:

    ts
    import * as React from "react";

    When the module does not explicitly specify a default export.

    For example, without allowSyntheticDefaultImports as true:

    // @filename: utilFunctions.js
    Module '"/home/runner/work/TypeScript-Website/TypeScript-Website/packages/typescriptlang-org/utilFunctions"' has no default export.1192Module '"/home/runner/work/TypeScript-Website/TypeScript-Website/packages/typescriptlang-org/utilFunctions"' has no default export.
    const getStringLength = (str) => str.length;
    module.exports = {
    getStringLength,
    };
    // @filename: index.ts
    import utils from "./utilFunctions";
    const count = utils.getStringLength("Check JS");
    Try

    This code raises an error 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;
    module.exports.default = allFunctions;

    This flag 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.

    # Allow Umd Global Access - allowUmdGlobalAccess

    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.

    • Default:

      false

    • Released:

      3.5

    # Base Url - baseUrl

    절대 경로 참조가 아닌 모듈 이름을 해결하기 위한 기본 디렉터리를 설정할 수 있습니다.

    절대 경로로 해결하기 위한 루트 폴더를 정의할 수도 있습니다. 예를 들면,

    baseUrl ├── ex.ts ├── hello │ └── world.ts └── tsconfig.json

    이 프로젝트에서"baseUrl": "./"을 사용하면, TypeScript는tsconfig.json과 같은 폴더에서 시작하는 파일을 찾습니다.

    ts
    import { helloWorld } from "hello/world";
    console.log(helloWorld);

    항상 사용하는 "../" 또는 "./"같은 import에 질렸거나, 파일을 이동해서 변경해야 할 때, 사용할 수 있는 좋은 방법입니다.

      # ES Module Interop - esModuleInterop

      By default (with esModuleInterop false or not set) TypeScript treats CommonJS/AMD/UMD modules similar to ES6 modules. In doing this, there are two parts in particular which turned out to be flawed assumptions:

      • a namespace import like import * as moment from "moment" acts the same as const moment = require("moment")
      • a default import like import moment from "moment" acts the same as const moment = require("moment").default

      This mis-match causes these two issues:

      • the ES6 modules spec states that a namespace import (import * as x) can only be an object, by having TypeScript treating it the same as = require("x") then TypeScript allowed for the import to be treated as a function and be callable. This breaks the spec’s recommendations.
      • while accurate to the ES6 modules spec, most libraries with CommonJS/AMD/UMD modules didn’t conform as strictly as TypeScript’s implementation.

      Turning on esModuleInterop will fix both of these problems in the code transpiled by TypeScript. The first changes the behavior in the compiler,the second is fixed by two new helper functions which provide a shim to ensure compatibility in the emitted JavaScript:

      ts
      import * as fs from "fs";
      import _ from "lodash";
      fs.readFileSync("file.txt", "utf8");
      _.chunk(["a", "b", "c", "d"], 2);

      With esModuleInterop disabled:

      "use strict";
      Object.defineProperty(exports, "__esModule", { value: true });
      const fs = require("fs");
      const lodash_1 = require("lodash");
      fs.readFileSync("file.txt", "utf8");
      lodash_1.default.chunk(["a", "b", "c", "d"], 2);
      Try

      With esModuleInterop set to true:

      "use strict";
      var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
      if (k2 === undefined) k2 = k;
      Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
      }) : (function(o, m, k, k2) {
      if (k2 === undefined) k2 = k;
      o[k2] = m[k];
      }));
      var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
      }) : function(o, v) {
      o["default"] = v;
      });
      var __importStar = (this && this.__importStar) || function (mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
      __setModuleDefault(result, mod);
      return result;
      };
      var __importDefault = (this && this.__importDefault) || function (mod) {
      return (mod && mod.__esModule) ? mod : { "default": mod };
      };
      Object.defineProperty(exports, "__esModule", { value: true });
      const fs = __importStar(require("fs"));
      const lodash_1 = __importDefault(require("lodash"));
      fs.readFileSync("file.txt", "utf8");
      lodash_1.default.chunk(["a", "b", "c", "d"], 2);
      Try

      Note: The namespace import import * as fs from "fs" only accounts for properties which are owned (basically properties set on the object and not via the prototype chain) on the imported object. If the module you’re importing defines its API using inherited properties, you need to use the default import form (import fs from "fs"), or disable esModuleInterop.

      Note: You can make JS emit terser by enabling importHelpers:

      "use strict";
      Object.defineProperty(exports, "__esModule", { value: true });
      const tslib_1 = require("tslib");
      const fs = (0, tslib_1.__importStar)(require("fs"));
      const lodash_1 = (0, tslib_1.__importDefault)(require("lodash"));
      fs.readFileSync("file.txt", "utf8");
      lodash_1.default.chunk(["a", "b", "c", "d"], 2);
      Try

      Enabling esModuleInterop will also enable allowSyntheticDefaultImports.

      # Module Resolution - moduleResolution

      Specify the module resolution strategy: 'node' (Node.js) or 'classic' (used in TypeScript before the release of 1.6). You probably won’t need to use classic in modern code.

      There is a handbook reference page on Module Resolution

      • Default:

        module === AMD or UMD or System or ES6, then Classic

        Otherwise Node

      • Related:

        module

      # Paths - paths

      가져오기를 baseUrl 과 관련된 조회 위치로 다시 매핑하는 일련의 항목으로, handbookpaths 의 더 많은 coverage가 수록되어 있습니다.

      paths 를 사용하면 Typescript가 require/import 에서 가져오기를 해결하는 방법을 선언 할 수 있습니다.

      {
      "": ".", // 이 옵션은 반드시 "paths"가 명확할 때 지정해야 합니다.
      "": {
      "jquery": ["node_modules/jquery/dist/jquery"] // 이 매핑은 "baseUrl"에 상대적입니다.
      }
      }
      }

      이렇게하면import "jquery"를 작성할 수 있고 모든 올바른 입력을 로컬에서 얻을 수 있습니다.

      {
      "": "src",
      "": {
      "app/*": ["app/*"],
      "config/*": ["app/_config/*"],
      "environment/*": ["environments/*"],
      "shared/*": ["app/_shared/*"],
      "helpers/*": ["helpers/*"],
      "tests/*": ["tests/*"]
      },
      }

      이렇게 하면 TypeScript 파일 resolver가 많은 custom prefix로 코드를 찾을 수 있도록 지원할 수 있습니다. 이 패턴을 사용하면 codebase 안에서 긴 상대 경로를 피할 수 있습니다.

        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. imports and /// <reference type="..." /> 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.

        • Default:

          false

        # Root Dirs - rootDirs

        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")
        {
        "": ["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.

        rootDirs can be used to provide a separate “type layer” to files that are not TypeScript or JavaScript by providing a home for generated .d.ts files in another folder. This is technique is useful for bundled applications where you use import of files that aren’t necessarily code:

        sh
        src
        └── index.ts
        └── css
        └── main.css
        └── navigation.css
        generated
        └── css
        └── main.css.d.ts
        └── navigation.css.d.ts
        {
        "": ["src", "generated"]
        }
        }

        This technique lets you generate types ahead of time for the non-code source files. Imports then work naturally based off the source file’s location. For example ./src/index.ts can import the file ./src/css/main.css and TypeScript will be aware of the bundler’s behavior for that filetype via the corresponding generated declaration file.

        // @filename: index.ts
        import { appClass } from "./main.css";
        Try

        # Type Roots - typeRoots

        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:

        {
        "": ["./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.

        # Types - types

        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 in the global scope. For instance:

        {
        "": ["node", "jest", "express"]
        }
        }

        This tsconfig.json file will only include ./node_modules/@types/node, ./node_modules/@types/jest and ./node_modules/@types/express. Other packages under node_modules/@types/* will not be included.

        What does this affect?

        This option does not affect how @types/* are included in your application code, for example if you had the above compilerOptions example with code like:

        ts
        import * as moment from "moment";
        moment().format("MMMM Do YYYY, h:mm:ss a");

        The moment import would be fully typed.

        When you have this option set, by not including a module in the types array it:

        • Will not add globals to your project (e.g process in node, or expect in Jest)
        • Will not have exports appear as auto-import recommendations

        This feature differs from typeRoots in that it is about specifying only the exact types you want included, whereas typeRoots supports saying you want particular folders.

        #Source Maps

        TypeScript는 JavaScript 소스 맵 표준에 적합한 추가적인 파일을 생성하여, 개발자가 이해할 수 있는 풍부한 디버깅 툴과 충돌 보고서를 제공합니다.

        위 기능이 필요한 파일과 함께 해당 .map 파일이 생성됩니다.

        # Inline Source Map - inlineSourceMap

        When set, instead of writing out a .js.map file to provide source maps, TypeScript will embed the source map content in the .js files. 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.

        For example, with this TypeScript:

        ts
        const helloWorld = "hi";
        console.log(helloWorld);

        Converts to this JavaScript:

        "use strict";
        const helloWorld = "hi";
        console.log(helloWorld);
        Try

        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.

        "use strict";
        const helloWorld = "hi";
        console.log(helloWorld);
        //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJpbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsTUFBTSxVQUFVLEdBQUcsSUFBSSxDQUFDO0FBQ3hCLE9BQU8sQ0FBQyxHQUFHLENBQUMsVUFBVSxDQUFDLENBQUMifQ==
        Try
        • Default:

          false

        • Released:

          1.5

        # Inline Sources - inlineSources

        When set, TypeScript will include the original content of the .ts file as an embedded string in the source map. This is often useful in the same cases as inlineSourceMap.

        Requires either sourceMap or inlineSourceMap to be set.

        For example, with this TypeScript:

        const helloWorld = "hi";
        console.log(helloWorld);
        Try

        By default converts to this JavaScript:

        "use strict";
        const helloWorld = "hi";
        console.log(helloWorld);
        Try

        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 because the source-map now contains the original source code also.

        "use strict";
        const helloWorld = "hi";
        console.log(helloWorld);
        //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJpbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsTUFBTSxVQUFVLEdBQUcsSUFBSSxDQUFDO0FBQ3hCLE9BQU8sQ0FBQyxHQUFHLENBQUMsVUFBVSxDQUFDLENBQUMiLCJzb3VyY2VzQ29udGVudCI6WyJjb25zdCBoZWxsb1dvcmxkID0gXCJoaVwiO1xuY29uc29sZS5sb2coaGVsbG9Xb3JsZCk7Il19
        Try
        • Default:

          false

        • Released:

          1.5

        # Map Root - mapRoot

        Specify the location where debugger should locate map files instead of generated locations. This string is treated verbatim inside the source-map, for example:

        {
        "": true,
        "": "https://my-website.com/debug/sourcemaps/"
        }
        }

        Would declare that index.js will have sourcemaps at https://my-website.com/debug/sourcemaps/index.js.map.

          # Source Root - sourceRoot

          소스의 상대 위치 대신 디버거가 TypeScript 파일을 찾을 위치를 지정합니다. 이 문자열은 경로 또는 URL을 사용할 수 있는 소스-맵 내에서 그대로 처리됩니다:

          {
          "": true,
          "": "https://my-website.com/debug/source/"
          }
          }

          index.jshttps://my-website.com/debug/source/index.ts 위치에 소스 파일이 있다고 명시해야 합니다.

            #Linter Checks

            컴파일러 vs 린터의 경계를 넘는 추가 검사 모음입니다. 좀 더 상세한 규칙을 원한다면 이 옵션보다는 eslint 같은 도구 사용을 추천합니다.

            # No Fallthrough Cases In Switch - noFallthroughCasesInSwitch

            Report errors for fallthrough cases in switch statements. 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.

            const a: number = 6;
            switch (a) {
            case 0:
            Fallthrough case in switch.7029Fallthrough case in switch.
            console.log("even");
            case 1:
            console.log("odd");
            break;
            }
            Try
            • Default:

              false

            • Released:

              1.8

            # noImplicitOverride - noImplicitOverride

            When working with classes which use inheritance, it’s possible for a sub-class to get “out of sync” with the functions it overloads when they are renamed in the base class.

            For example, imagine you are modeling a music album syncing system:

            class Album {
            download() {
            // Default behavior
            }
            }
            class SharedAlbum extends Album {
            download() {
            // Override to get info from many sources
            }
            }
            Try

            Then when you add support for machine-learning generated playlists, you refactor the Album class to have a ‘setup’ function instead:

            class Album {
            setup() {
            // Default behavior
            }
            }
            class MLAlbum extends Album {
            setup() {
            // Override to get info from algorithm
            }
            }
            class SharedAlbum extends Album {
            download() {
            // Override to get info from many sources
            }
            }
            Try

            In this case, TypeScript has provided no warning that download on SharedAlbum expected to override a function in the base class.

            Using noImplicitOverride you can ensure that the sub-classes never go out of sync, by ensuring that functions which override include the keyword override.

            The following example has noImplicitOverride enabled, and you can see the error received when override is missing:

            class Album {
            setup() {}
            }
            class MLAlbum extends Album {
            override setup() {}
            }
            class SharedAlbum extends Album {
            setup() {}
            This member must have an 'override' modifier because it overrides a member in the base class 'Album'.4114This member must have an 'override' modifier because it overrides a member in the base class 'Album'.
            }
            Try

            # No Implicit Returns - noImplicitReturns

            When enabled, TypeScript will check all code paths in a function to ensure they return a value.

            function lookupHeadphonesManufacturer(color: "blue" | "black"): string {
            Function lacks ending return statement and return type does not include 'undefined'.2366Function lacks ending return statement and return type does not include 'undefined'.
            if (color === "blue") {
            return "beats";
            } else {
            "bose";
            }
            }
            Try
            • Default:

              false

            • Released:

              1.8

            # noPropertyAccessFromIndexSignature - noPropertyAccessFromIndexSignature

            This setting ensures consistency between accessing a field via the “dot” (obj.key) syntax, and “indexed” (obj["key"]) and the way which the property is declared in the type.

            Without this flag, TypeScript will allow you to use the dot syntax to access fields which are not defined:

            interface GameSettings {
            // Known up-front properties
            speed: "fast" | "medium" | "slow";
            quality: "high" | "low";
            // Assume anything unknown to the interface
            // is a string.
            [key: string]: string;
            }
            const settings = getSettings();
            settings.speed;
            (property) GameSettings.speed: "fast" | "medium" | "slow"
            settings.quality;
            (property) GameSettings.quality: "high" | "low"
            // Unknown key accessors are allowed on
            // this object, and are `string`
            settings.username;
            string
            Try

            Turning the flag on will raise an error because the unknown field uses dot syntax instead of indexed syntax.

            const settings = getSettings();
            settings.speed;
            settings.quality;
            // This would need to be settings["username"];
            settings.username;
            Property 'username' comes from an index signature, so it must be accessed with ['username'].4111Property 'username' comes from an index signature, so it must be accessed with ['username'].
            string
            Try

            The goal of this flag is to signal intent in your calling syntax about how certain you are this property exists.

            • Default:

              false

            • Released:

              4.2

            # noUncheckedIndexedAccess - noUncheckedIndexedAccess

            TypeScript has a way to describe objects which have unknown keys but known values on an object, via index signatures.

            interface EnvironmentVars {
            NAME: string;
            OS: string;
            // Unknown properties are covered by this index signature.
            [propName: string]: string;
            }
            declare const env: EnvironmentVars;
            // Declared as existing
            const sysName = env.NAME;
            const os = env.OS;
            const os: string
            // Not declared, but because of the index
            // signature, then it is considered a string
            const nodeEnv = env.NODE_ENV;
            const nodeEnv: string
            Try

            Turning on noUncheckedIndexedAccess will add undefined to any un-declared field in the type.

            declare const env: EnvironmentVars;
            // Declared as existing
            const sysName = env.NAME;
            const os = env.OS;
            const os: string
            // Not declared, but because of the index
            // signature, then it is considered a string
            const nodeEnv = env.NODE_ENV;
            const nodeEnv: string | undefined
            Try

            # No Unused Locals - noUnusedLocals

            Report errors on unused local variables.

            const createKeyboard = (modelID: number) => {
            const defaultModelID = 23;
            'defaultModelID' is declared but its value is never read.6133'defaultModelID' is declared but its value is never read.
            return { type: "keyboard", modelID };
            };
            Try
            • Default:

              false

            • Released:

              2.0

            # No Unused Parameters - noUnusedParameters

            Report errors on unused parameters in functions.

            const createDefaultKeyboard = (modelID: number) => {
            'modelID' is declared but its value is never read.6133'modelID' is declared but its value is never read.
            const defaultModelID = 23;
            return { type: "keyboard", modelID: defaultModelID };
            };
            Try
            • Default:

              false

            • Released:

              2.0

            #Experimental

            TypeScript는 JavaScript 언어에 확실히 추가될 기능만 포함하기 위해 노력합니다.

            어떤 기능은 이 규칙에서 예외가 될 만큼 강력한 경우가 있으며, 실험적인 컴파일러 플래그로 존재합니다. 이러한 기능이 포함된 버전은 JavaScript 언어에 추가될 때 의도와 다를 수 있기 때문에 조심스럽게 간주됩니다.

            # Emit Decorator Metadata - emitDecoratorMetadata

            Enables experimental support for emitting type metadata for decorators which works with the module reflect-metadata.

            For example, here is the JavaScript

            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();
            Try

            With emitDecoratorMetadata not set to true (default):

            "use strict";
            var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
            var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
            if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
            else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
            return c > 3 && r && Object.defineProperty(target, key, r), r;
            };
            function LogMethod(target, propertyKey, descriptor) {
            console.log(target);
            console.log(propertyKey);
            console.log(descriptor);
            }
            class Demo {
            foo(bar) {
            // do nothing
            }
            }
            __decorate([
            LogMethod
            ], Demo.prototype, "foo", null);
            const demo = new Demo();
            Try

            With emitDecoratorMetadata set to true:

            "use strict";
            var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
            var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
            if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
            else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
            return c > 3 && r && Object.defineProperty(target, key, r), r;
            };
            var __metadata = (this && this.__metadata) || function (k, v) {
            if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
            };
            function LogMethod(target, propertyKey, descriptor) {
            console.log(target);
            console.log(propertyKey);
            console.log(descriptor);
            }
            class Demo {
            foo(bar) {
            // do nothing
            }
            }
            __decorate([
            LogMethod,
            __metadata("design:type", Function),
            __metadata("design:paramtypes", [Number]),
            __metadata("design:returntype", void 0)
            ], Demo.prototype, "foo", null);
            const demo = new Demo();
            Try

            # Experimental Decorators - experimentalDecorators

            Enables experimental support for decorators, which is in stage 2 of the TC39 standardization process.

            Decorators are a language feature which hasn’t yet been fully ratified into the JavaScript specification. This means that the implementation version in TypeScript may differ from the implementation in JavaScript when it it decided by TC39.

            You can find out more about decorator support in TypeScript in the handbook.

            #Advanced

            디버깅에 도움을 주는 플래그

            # Allow Unreachable Code - allowUnreachableCode

            When:

            • undefined (default) provide suggestions as warnings to editors
            • true unreachable code is ignored
            • false 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:

            function fn(n: number) {
            if (n > 5) {
            return true;
            } else {
            return false;
            }
            return true;
            Unreachable code detected.7027Unreachable code detected.
            }
            Try

            This does not affect errors on the basis of code which appears to be unreachable due to type analysis.

            • Default:

              undefined

            • Released:

              1.8

            # Allow Unused Labels - allowUnusedLabels

            When:

            • undefined (default) provide suggestions as warnings to editors
            • true unused labels are ignored
            • false raises compiler errors about unused labels

            Labels are very rare in JavaScript and typically indicate an attempt to write an object literal:

            function verifyAge(age: number) {
            // Forgot 'return' statement
            if (age > 18) {
            verified: true;
            Unused label.7028Unused label.
            }
            }
            Try
            • Default:

              undefined

            • Released:

              1.8

            # 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.

            # Charset - charset

            이전 버전의 TypeScript에서는, 디스크에서 텍스트 파일을 읽을 때 인코딩 방식을 제어했습니다. 현재 TypeScript는 UTF-8 인코딩을 전제로 합니다. 하지만 UTF-16 (BE 와 LE) 또는 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

            # 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.

            # 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.

            # 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.

            # 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.

            # 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.

            # 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 of include

            This option is intended for debugging how a file has become a part of your compile.

            # Extended Diagnostics - extendedDiagnostics

            You can use this flag to discover where TypeScript is spending its 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.

            # 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:

              3.7

            # Imports Not Used As Values - importsNotUsedAsValues

            This flag controls how import works, there are 3 different options:

            • remove: The default behavior of dropping import statements which only reference types.
            • preserve: Preserves all import 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,
              error

            • Released:

              3.8

            # 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:

            "use strict";
            Object.defineProperty(exports, "__esModule", { value: true });
            const preact_1 = require("preact");
            const HelloWorld = () => (0, preact_1.h)("div", null, "Hello");
            Try

            This option can be used on a per-file basis too similar to Babel’s /** @jsx h */ directive.

            /** @jsx h */
            import { h } from "preact";
            const HelloWorld = () => <div>Hello</div>;
            Try

            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.

            # jsxFragmentFactory - jsxFragmentFactory

            Fragment와 같이, JsxFactory 컴파일러 옵션이 지정된 react JSX 출력을 목표로 할 때 사용할 JSX 프래그먼트 팩토리 함수를 지정합니다.

            예를 들어 이 TSConfig의 경우:

            {
            "": "esnext",
            "": "commonjs",
            "": "react",
            "": "h",
            "": "Fragment"
            }
            }

            이 TSX 파일은:

            tsx
            import { h, Fragment } from "preact";
            const HelloWorld = () => (
            <>
            <div>Hello</div>
            </>
            );

            다음과 같을 것입니다:

            "use strict";
            Object.defineProperty(exports, "__esModule", { value: true });
            const preact_1 = require("preact");
            const HelloWorld = () => ((0, preact_1.h)(preact_1.Fragment, null,
            (0, preact_1.h)("div", null, "Hello")));
            Try

            이 옵션은 바벨의 /* @jsxFrag h */ 지시문과 매우 유사한 파일 단위로 사용이 가능합니다.

            예를 들어:

            /** @jsx h */
            /** @jsxFrag Fragment */
            import { h, Fragment } from "preact";
            const HelloWorld = () => (
            <>
            <div>Hello</div>
            </>
            );
            Try

            # jsxImportSource - jsxImportSource

            Typescript 4.1 버전에 소개된 jsx"react-jsx" 또는 "react-jsxdev"로 사용할 때, jsxjsxs 팩터리 함수를 import 하는데 사용할 모듈 지정자를 선언합니다.

            React 17에서, 라이브러리는 독립된 import를 통하여 새로운 형태의 JSX 변환을 지원해 줍니다.

            예를 들어:

            tsx
            import React from "react";
            function App() {
            return <h1>Hello World</h1>;
            }

            TSConfig 사용할 때:

            {
            "": "esnext",
            "": "commonjs",
            "": "react-jsx"
            }
            }

            TypeScript에서 컴파일 된 JavaScript는:

            "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 (0, jsx_runtime_1.jsx)("h1", { children: "Hello World" }, void 0);
            }
            Try

            예를 들어, "jsxImportSource": "preact"를 사용하고 싶으시면, 다음과 같은 tsconfig를 이용하시면 됩니다:

            {
            "": "esnext",
            "": "commonjs",
            "": "react-jsx",
            "": "preact",
            "": ["preact"]
            }
            }

            다음과 같은 코드를 생성합니다:

            "use strict";
            Object.defineProperty(exports, "__esModule", { value: true });
            exports.App = void 0;
            const jsx_runtime_1 = require("preact/jsx-runtime");
            function App() {
            return (0, jsx_runtime_1.jsx)("h1", { children: "Hello World" }, void 0);
            }
            exports.App = App;
            Try

            또는, 파일 별 프래그마(per-file pragma)를 이용하여 다음과 같은 옵션을 설정할 수 있습니다:

            tsx
            /** @jsxImportSource preact */
            export function App() {
            return <h1>Hello World</h1>;
            }

            _jsx팩토리를 위한 import로서 preact/jsx-runtime를 추가합니다.

            노트: 의도한 대로 작동이 되려면, tsx파일은 export 또는 import를 추가해야만, 모듈로 간주됩니다.

            # 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:

              2.9

            # 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

            컴파일하는 파일 이름을 출력합니다. 이 기능은 TypeScript에 예상한 파일이 포함되어 있는지 확실하지 않을 때 유용합니다.

            예를들면:

            example ├── index.ts ├── package.json └── tsconfig.json

            다음과 같습니다:

            {
            "": true
            }
            }

            echo paths는 다음과 같습니다:

            $ 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

            TypeScript 4.2 버전을 사용할 경우 explainFiles을 참조하십시오. 파일이 추가된 이유에 대한 설명 또한 제공합니다.

            # 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

            파일을 내보낼 때 줄바꿈의 끝을 지정합니다 : ‘CRLF’ (docs) 또는 ‘LF’ (unix).

            • Default:

              Platform specific

            • Released:

              1.5

            # 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:

            const getAPI = async (url: string) => {
            // Get API
            return {};
            };
            Try

            Which creates quite a lot of JavaScript:

            "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 API
            return [2 /*return*/, {}];
            });
            }); };
            Try

            Which can be switched out with your own globals via this flag:

            "use strict";
            var getAPI = function (url) { return __awaiter(void 0, void 0, void 0, function () {
            return __generator(this, function (_a) {
            // Get API
            return [2 /*return*/, {}];
            });
            }); };
            Try

            # 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:

              1.4

            # No Error Truncation - noErrorTruncation

            Do not truncate error messages.

            With false, the default.

            var x: {
            propertyWithAnExceedinglyLongName1: string;
            propertyWithAnExceedinglyLongName2: string;
            propertyWithAnExceedinglyLongName3: string;
            propertyWithAnExceedinglyLongName4: string;
            propertyWithAnExceedinglyLongName5: string;
            propertyWithAnExceedinglyLongName6: string;
            propertyWithAnExceedinglyLongName7: string;
            propertyWithAnExceedinglyLongName8: string;
            };
            // String representation of type of 'x' should be truncated in error message
            var s: string = x;
            Type '{ propertyWithAnExceedinglyLongName1: string; propertyWithAnExceedinglyLongName2: string; propertyWithAnExceedinglyLongName3: string; propertyWithAnExceedinglyLongName4: string; propertyWithAnExceedinglyLongName5: string; propertyWithAnExceedinglyLongName6: string; propertyWithAnExceedinglyLongName7: string; propert...' is not assignable to type 'string'.
            Variable 'x' is used before being assigned.
            2322
            2454
            Type '{ propertyWithAnExceedinglyLongName1: string; propertyWithAnExceedinglyLongName2: string; propertyWithAnExceedinglyLongName3: string; propertyWithAnExceedinglyLongName4: string; propertyWithAnExceedinglyLongName5: string; propertyWithAnExceedinglyLongName6: string; propertyWithAnExceedinglyLongName7: string; propert...' is not assignable to type 'string'.
            Variable 'x' is used before being assigned.
            Try

            With true

            var x: {
            propertyWithAnExceedinglyLongName1: string;
            propertyWithAnExceedinglyLongName2: string;
            propertyWithAnExceedinglyLongName3: string;
            propertyWithAnExceedinglyLongName4: string;
            propertyWithAnExceedinglyLongName5: string;
            propertyWithAnExceedinglyLongName6: string;
            propertyWithAnExceedinglyLongName7: string;
            propertyWithAnExceedinglyLongName8: string;
            };
            // String representation of type of 'x' should be truncated in error message
            var s: string = x;
            Type '{ propertyWithAnExceedinglyLongName1: string; propertyWithAnExceedinglyLongName2: string; propertyWithAnExceedinglyLongName3: string; propertyWithAnExceedinglyLongName4: string; propertyWithAnExceedinglyLongName5: string; propertyWithAnExceedinglyLongName6: string; propertyWithAnExceedinglyLongName7: string; propertyWithAnExceedinglyLongName8: string; }' is not assignable to type 'string'.
            Variable 'x' is used before being assigned.
            2322
            2454
            Type '{ propertyWithAnExceedinglyLongName1: string; propertyWithAnExceedinglyLongName2: string; propertyWithAnExceedinglyLongName3: string; propertyWithAnExceedinglyLongName4: string; propertyWithAnExceedinglyLongName5: string; propertyWithAnExceedinglyLongName6: string; propertyWithAnExceedinglyLongName7: string; propertyWithAnExceedinglyLongName8: string; }' is not assignable to type 'string'.
            Variable 'x' is used before being assigned.
            Try
            • 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.

            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;
            });
            Try
            • Default:

              false

            # No Lib - noLib

            Disables the automatic inclusion of any library files. If this option is set, lib is ignored.

            TypeScript cannot compile anything without a set of interfaces for key primitives like: Array, Boolean,Function, IArguments, Number, Object, RegExp, and String. It is expected that if you use noLib you will be including your own type definitions for these.

            • Default:

              false

            • Related:

              lib

            # 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.

            type A = <T, U>(x: T, y: U) => [T, U];
            type B = <S>(x: S, y: S) => [S, S];
            function f(a: A, b: B) {
            b = a; // Ok
            a = b; // Error
            Type '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'.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:

              2.4

            # Out - out

            대신에 outFile 을 사용하세요.

            out 옵션은 예측 불가능하거나 일관되지 않은 방식으로 최종 파일 위치를 계산합니다. 이 옵션은 이전 버전과의 호환성을 위해 유지될 뿐 사용을 권장하지 않습니다.

            # Preserve Const Enums - preserveConstEnums

            Do not erase const enum declarations in generated code. const enums 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 enum Album {
            JimmyEatWorldFutures = 1,
            TubRingZooHypothesis = 2,
            DogFashionDiscoAdultery = 3,
            }
            const selectedAlbum = Album.JimmyEatWorldFutures;
            if (selectedAlbum === Album.JimmyEatWorldFutures) {
            console.log("That is a great choice.");
            }
            Try

            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.

            "use strict";
            const selectedAlbum = 1 /* JimmyEatWorldFutures */;
            if (selectedAlbum === 1 /* JimmyEatWorldFutures */) {
            console.log("That is a great choice.");
            }
            Try

            With preserveConstEnums set to true, the enum exists at runtime and the numbers are still emitted.

            "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.");
            }
            Try

            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.json
            Cannot 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.ts
            import settings from "./settings.json";
            settings.debug === true;
            settings.dry === 2;
            Try

            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.ts
            import settings from "./settings.json";
            settings.debug === true;
            settings.dry === 2;
            Try
            • 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:

              2.0

            # Strip Internal - stripInternal

            Do not emit declarations for code that has an @internal annotation in its 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 const daysInAWeek = 7;
            /** Calculate how much someone earns in a week */
            export function weeklySalary(dayRate: number) {
            return daysInAWeek * dayRate;
            }
            Try

            With the flag set to false (default):

            /**
            * 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;
            Try

            With stripInternal set to true the d.ts emitted will be redacted.

            /** Calculate how much someone earns in a week */
            export declare function weeklySalary(dayRate: number): number;
            Try

            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:

            type Point = { x: number; y: number };
            const p: Point = { x: 1, y: 3, m: 10 };
            Type '{ 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'.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:

            const obj = { x: 10 };
            console.log(obj["foo"]);
            Element 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; }'.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:

            const obj = { x: 10 };
            // @ts-ignore
            console.log(obj["foo"]);
            Try

            # Trace Resolution - traceResolution

            사용자가 모듈이 포함되지 않은 이유를 디버깅하고자 할 때. traceResolutionstrue로 설정하여 처리된 각 파일의 처리 과정에 대한 TypeScript 출력 정보를 얻을 수 있습니다.

            핸드북에서 이에 대한 자세한 내용을 볼 수 있습니다.

            • Default:

              false

            • Released:

              2.0

            # 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:

              3.7

            #Command Line

            # Preserve Watch Output - preserveWatchOutput

            Whether to keep outdated console output in watch mode instead of clearing the screen every time a change happened.

            • Default:

              false

            • Status:

              internal

            # Pretty - pretty

            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.

            • Default:

              true

            Watch Options

            You can configure the how TypeScript --watch works. This section is mainly for handling case where fs.watch and fs.watchFile have additional constraints like on Linux. You can read more at Configuring Watch.

            # watchFile - watchFile

            The strategy for how individual files are watched.

            • fixedPollingInterval: Check every file for changes several times a second at a fixed interval.
            • priorityPollingInterval: Check every file for changes several times a second, but use heuristics to check certain types of files less frequently than others.
            • dynamicPriorityPolling: Use a dynamic queue where less-frequently modified files will be checked less often.
            • useFsEvents (the default): Attempt to use the operating system/file system’s native events for file changes.
            • useFsEventsOnParentDirectory: Attempt to use the operating system/file system’s native events to listen for changes on a file’s parent directory
            • Allowed:

              fixedPollingInterval,
              priorityPollingInterval,
              dynamicPriorityPolling,
              useFsEvents,
              useFsEventsOnParentDirectory

            • Released:

              3.8

            # watchDirectory - watchDirectory

            The strategy for how entire directory trees are watched under systems that lack recursive file-watching functionality.

            • fixedPollingInterval: Check every directory for changes several times a second at a fixed interval.
            • dynamicPriorityPolling: Use a dynamic queue where less-frequently modified directories will be checked less often.
            • useFsEvents (the default): Attempt to use the operating system/file system’s native events for directory changes.
            • Allowed:

              fixedPollingInterval,
              dynamicPriorityPolling,
              useFsEvents

            • Released:

              3.8

            # fallbackPolling - fallbackPolling

            When using file system events, this option specifies the polling strategy that gets used when the system runs out of native file watchers and/or doesn’t support native file watchers.

            • fixedPollingInterval: Check every file for changes several times a second at a fixed interval.
            • priorityPollingInterval: Check every file for changes several times a second, but use heuristics to check certain types of files less frequently than others.
            • dynamicPriorityPolling: Use a dynamic queue where less-frequently modified files will be checked less often.
            • synchronousWatchDirectory: Disable deferred watching on directories. Deferred watching is useful when lots of file changes might occur at once (e.g. a change in node_modules from running npm install), but you might want to disable it with this flag for some less-common setups.
            • Allowed:

              fixedPollingInterval,
              priorityPollingInterval,
              dynamicPriorityPolling

            • Released:

              3.8

            # synchronousWatchDirectory - synchronousWatchDirectory

            Synchronously call callbacks and update the state of directory watchers on platforms that don`t support recursive watching natively. Instead of giving a small timeout to allow for potentially multiple edits to occur on a file.

            {
            "watchOptions": {
            }
            }

              # excludeDirectories - excludeDirectories

              You can use excludeFiles to drastically reduce the number of files which are watched during --watch. This can be a useful way to reduce the number of open file which TypeScript tracks on Linux.

              {
              "watchOptions": {
              "": ["**/node_modules", "_build", "temp/*"]
              }
              }

                # excludeFiles - excludeFiles

                You can use excludeFiles to remove a set of specific files from the files which are watched.

                {
                "watchOptions": {
                "": ["temp/file.ts"]
                }
                }

                  Type Acquisition

                  Type Acquisition is only important for JavaScript projects. In TypeScript projects you need to include the types in your projects explicitly. However, for JavaScript projects, the TypeScript tooling will download types for your modules in the background and outside of your node_modules folder.

                  # enable - enable

                  Offers a config for disabling type-acquisition in JavaScript projects:

                  ts
                  {
                  "typeAcquisition": {
                  "enable": false
                  }
                  }

                  This could potentially remove all of the editor auto-completion for your project, if you want to get them back, you can use the Type Search to find @types packages or packages with types in them.

                    # Include - include

                    If you have a JavaScript project where TypeScript needs additional guidance to understand global dependencies, or have disabled the built-in inference via disableFilenameBasedTypeAcquisition.

                    You can use include to specify which types should be used from DefinitelyTyped:

                    json
                    {
                    "typeAcquisition": {
                    "include": ["jquery"]
                    }
                    }

                    # Exclude - exclude

                    Offers a config for disabling the type-acquisition for a certain module in JavaScript projects. This can be useful for projects which include other libraries in testing infrastructure which aren’t needed in the main application.

                    json
                    {
                    "typeAcquisition": {
                    "exclude": ["jest", "mocha"]
                    }
                    }

                    # disableFilenameBasedTypeAcquisition - disableFilenameBasedTypeAcquisition

                    TypeScript’s type acquisition can infer what types should be added based on filenames in a project. This means that having a file like jquery.js in your project would automatically download the types for JQuery from DefinitelyTyped.

                    You can disable this via disableFilenameBasedTypeAcquisition.

                    json
                    {
                    "typeAcquisition": {
                    "disableFilenameBasedTypeAcquisition": true
                    }
                    }