Compiler Options

"compilerOptions"

JavaScript Support
  1. allowJs,
  2. checkJs and
  3. maxNodeModuleJsDepth
Editor Support
  1. disableSizeLimit and
  2. plugins
コマンドライン

    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"
    ]
    }

    このオプションは、プロジェクトが少数のファイルから構成されていて、グロブパターンを必要としない場合で有用です。 グロブパターンが必要な場合、includeを利用してください。

    # Extends - extends

    extendsの値は、別の継承対象の設定ファイルへのパスを含む文字列です。 Node.js におけるモジュール解決の流儀が用いられます。

    ベースとなるファイルからの設定が最初に読み込まれ、続いて継承ファイルの設定によってオーバーライドされます。設定ファイル内のすべての相対パスは、元の設定ファイルを起点として解決されます。

    継承した設定ファイルのfilesincludeおよびexcludeはベースとなる設定ファイルの内容を上書きします。 また、継承における循環参照は許容されません。

    configs/base.json:

    tsconfig.json:

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

    tsconfig.nostrictnull.json:

    {
    "": "./tsconfig",
    }
    }
    • 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はグロブパターンのためのワイルドカードをサポートしています:

    • * ゼロ個以上の文字列にマッチ(ディレクトリセパレータは除く)
    • ? 任意の 1 文字にマッチ(ディレクトリセパレータは除く)
    • **/ 任意階層の任意ディレクトリにマッチ

    グロブパターンがファイルの拡張子を含まない場合、サポートされる拡張子のみが含まれるようになります(例:.ts.tsx.d.tsはデフォルトでインクルードされ、.js.jsxallowJsが設定された場合のみインクルードされます)。

    # Exclude - exclude

    includeの解決時にスキップさせるファイル名やパターンのリストを指定します。

    重要: excludeincludeの結果として、どのファイルが含まれるべきかのみに影響を与えます。 excludeに指定されたファイルは、コードでのimporttypesでのインクルード、/// <reference ディレクティブ、filesリストの指定によって、コードベースの一部となり得ます。

    excludeはコードベースに含まれているファイルの読み込みを防ぐための仕組みではありません。include設定の結果を変更するだけです。

    # References - references

    プロジェクト参照は TypeScript のプログラムを小さい断片に分けて構造化するための手法です。 プロジェクト参照を用いると、ビルド時間やエディターとのインタラクションに必要な時間が大幅に改善され、コンポーネント間の論理分割が強制により、より洗練された方法でコードを整理できます。

    プロジェクト参照がどのように動作するかについては、このハンドブックのProject Referencesを読んでください。

    • Default:

      false

    コンパイラオプション

    これらのオプションは TypeScript の設定の大部分を占めており、TypeScript がどのように動作すべきかを扱います。

    #Type Checking

    # Allow Unreachable Code - allowUnreachableCode

    false に設定すると、到達不可能なコードに対する警告を無効化します。 この警告は、JavaScript 構文の利用によって到達不可能になり得るコードにのみ関係します。例えば:

    ts
    function fn(n: number) {
    if (n > 5) {
    return true;
    } else {
    return false;
    }
    return true;
    }

    "allowUnreachableCode": falseにすると、次のようになります:

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

    このオプションは、型の分析によって到達不可能と判断されたコードについてのエラーには影響しません。

    # Allow Unused Labels - allowUnusedLabels

    false にセットすると、利用していない Label についての警告を無効化します。

    JavaScript において Label を利用することは稀ですが、オブジェクトリテラルを記述しようとしたときに Label 構文になってしまうことがあります。

    ts
    function verifyAge(age: number) {
    // 'return'の記述が抜けている
    if (age > 18) {
    verified: true;
    Unused label.7028Unused label.
    }
    }
    Try

    # Always Strict - alwaysStrict

    ファイルを ECMAScript の strict モードで解釈し、各ファイルへ”use strict”を出力することを保証します。

    ECMAScript strictモードは ES5 で導入され、JavaScript エンジンが実行時にパフォーマンスを改善できるよう微調整されます。代わりにいくつかのエラーが無視されずにスローされるようになります。

    • Recommended
    • Default:

      true if strict; false otherwise.

    • Related:
    • Released:

      2.1

    # Exact Optional Property Types - exactOptionalPropertyTypes

    With exactOptionalPropertyTypes enabled, TypeScript applies stricter rules around how it handles properties on type or interfaces which have a ? prefix.

    For example, this interface declares that there is a property which can be one of two strings: ‘dark’ or ‘light’ or it should not be in the object.

    ts
    interface UserDefaults {
    // The absence of a value represents 'system'
    colorThemeOverride?: "dark" | "light";
    }

    Without this flag enabled, there are three values which you can set colorThemeOverride to be: “dark”, “light” and undefined.

    Setting the value to undefined will allow most JavaScript runtime checks for the existence to fail, which is effectively falsy. However, this isn’t quite accurate; colorThemeOverride: undefined is not the same as colorThemeOverride not being defined. For example, "colorThemeOverride" in settings would have different behavior with undefined as the key compared to not being defined.

    exactOptionalPropertyTypes makes TypeScript truly enforce the definition provided as an optional property:

    ts
    const settings = getUserSettings();
    settings.colorThemeOverride = "dark";
    settings.colorThemeOverride = "light";
     
    // But not:
    settings.colorThemeOverride = undefined;
    Type 'undefined' is not assignable to type '"dark" | "light"' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the type of the target.2412Type 'undefined' is not assignable to type '"dark" | "light"' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the type of the target.
    Try
    • Recommended
    • Released:

      4.4

    # No Fallthrough Cases In Switch - noFallthroughCasesInSwitch

    switch 文において、次の case へ処理を持ち越した場合にエラーを報告します。 switch 文内の空でない case 句がbreakまたはreturnを含むことを確約します。 これは、意図しない case への処理持ち越しによるバグを流出させない、ということ意味しています。

    ts
    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

    # No Implicit Any - noImplicitAny

    いくつかの型アノテーションが存在しないケースにおいて、TypeScript は変数の型が推論できないときに、any型へフォールバックします。

    このため、エラーを見逃す可能性があります。例えば:

    ts
    function fn(s) {
    // エラーにならない?
    console.log(s.subtr(3));
    }
    fn(42);
    Try

    ただし、noImplicitAnyを有効化すると、TypeScript は型がanyに推論されるときは常にエラーを発生させます:

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

      true if strict; false otherwise.

    • Related:

    # No Implicit Override - 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:

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

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

    ts
    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

    有効化すると、TypeScript は関数内のすべてのコードパスについて、値を返却していることをチェックします。

    ts
    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

    # No Implicit This - noImplicitThis

    暗黙的にany型となる this 式でエラーを発生させます。

    例えば、以下の Class はthis.widththis.heightにアクセスする関数を返しています。 しかし、getAreaFunctionの内側の関数内でのコンテキストにおけるthisは Rectangle のインスタンスではありません。

    ts
    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
    • Default:

      true if strict; false otherwise.

    • Related:
    • Released:

      2.0

    # No Property Access From Index Signature - 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:

    ts
    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;
    (index) GameSettings[string]: string
    Try

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

    ts
    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'].
    (index) GameSettings[string]: string
    Try

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

    # noUncheckedIndexedAccess - noUncheckedIndexedAccess

    TypeScript には、オブジェクトにおいて未知のキーを持ちながらも値が既知であるプロパティをインデックスシグネチャで記述する方法があります。

    ts
    interface EnvironmentVars {
    NAME: string;
    OS: string;
     
    // 未知のプロパティは、次のようなインデックスシグネチャで扱うことができます。
    [propName: string]: string;
    }
     
    declare const env: EnvironmentVars;
     
    // 既存のプロパティとして宣言されています
    const sysName = env.NAME;
    const os = env.OS;
    const os: string
     
    // 宣言されていませんが、インデックス
    // シグネチャのおかげで、stringとして扱われます
    const nodeEnv = env.NODE_ENV;
    const nodeEnv: string
    Try

    noUncheckedIndexedAccessをオンにすると、型の未定義のフィールドにundefinedが追加されます。

    ts
    declare const env: EnvironmentVars;
     
    // 既存のプロパティとして宣言されています
    const sysName = env.NAME;
    const os = env.OS;
    const os: string
     
    // 宣言されていませんが、インデックス
    // シグネチャのおかげで、stringとして扱われます
    const nodeEnv = env.NODE_ENV;
    const nodeEnv: string | undefined
    Try

    # No Unused Locals - noUnusedLocals

    利用されていないローカル変数について、エラーを報告します。

    ts
    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

    # No Unused Parameters - noUnusedParameters

    利用されていない関数のパラメータについて、エラーを報告します。

    ts
    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

    # Strict - strict

    strictフラグは、プログラムの正しさを強く保証するための幅広い型チェックの挙動を有効化します。 このオプションの有効化は、以降で述べるすべてのstrict モードファミリーオプションの有効化と等価です。 必要に応じて、個別の strict モードファミリーを無効化できます。

    今後の TypeScript のバージョンがこのフラグの配下により厳密なチェックを導入するかもしれません。この場合、TypeScript のアップグレードにより、プログラムに新しい種類のエラーが発見されることもあるでしょう。 適切かつ可能な場合、この挙動を無効化するための対応するフラグも追加されます。

    # Strict Bind Call Apply - strictBindCallApply

    設定されている場合、関数の組み込みメソッドのcallbindapplyについて、元となっている関数に対して正しい引数で呼び出されているかを TypeScript がチェックします:

    ts
    // strictBindCallApplyが有効な場合
    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

    設定されていない場合、これらの関数は任意の引数を受け取ってanyを返します:

    ts
    // strictBindCallApplyが無効な場合
    function fn(x: string) {
    return parseInt(x);
    }
     
    // Note: エラーになりません。戻り値の型は'any'です。
    const n = fn.call(undefined, false);
    Try
    • Recommended
    • Default:

      true if strict; false otherwise.

    • Related:
    • Released:

      3.2

    # Strict Function Types - strictFunctionTypes

    有効化すると、このフラグは関数のパラメータをより正しくチェックするようになります。

    次はstrictFunctionTypesが無効な場合の基本的な例です:

    ts
    function fn(x: string) {
    console.log("Hello, " + x.toLowerCase());
    }
     
    type StringOrNumberFunc = (ns: string | number) => void;
     
    // 安全でない代入
    let func: StringOrNumberFunc = fn;
    // 安全でない呼び出し - エラーとなります
    func(10);
    Try

    strictFunctionTypes有効化すると、エラーが正しく検知されます:

    ts
    function fn(x: string) {
    console.log("Hello, " + x.toLowerCase());
    }
     
    type StringOrNumberFunc = (ns: string | number) => void;
     
    // 安全でない代入は抑止されます
    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

    私達はこの機能を開発する際、本質的に安全でない Class 階層を数多く見つけました。中には DOM のものも含まれていました。 このため、この設定はfunction構文で記述された関数にのみ適用され、メソッドとして記述された関数には適用されません:

    ts
    type Methodish = {
    func(x: string | number): void;
    };
     
    function fn(x: string) {
    console.log("Hello, " + x.toLowerCase());
    }
     
    // 最終的に安全でない代入となりますが、エラー検知はされません
    const m: Methodish = {
    func: fn,
    };
    m.func(10);
    Try
    • Recommended
    • Default:

      true if strict; false otherwise.

    • Related:
    • Released:

      2.6

    # Strict Null Checks - strictNullChecks

    strictNullChecksfalseのとき、nullundefinedは言語により事実上無視されます。 これは実行時の予期しないエラーの原因となります。

    strictNullCheckstrueのとき、nullundefinedはそれ自身に明示的な型が与えられ、具体的な値を期待して利用しようとした場合にエラーとなります。

    例えば、次の TypeScript コードのusers.findは実際にユーザーを見つけられる保証がありません。 しかし、ユーザーを見つけられたかのようにコードを書くことができます:

    ts
    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

    strictNullCheckstrueにすると、loggedInUserを利用する前に存在を確認していないことを示すエラーが発生します。

    ts
    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);
    'loggedInUser' is possibly 'undefined'.18048'loggedInUser' is possibly 'undefined'.
    Try

    単純化してみると配列のfind関数が次のようになっていることから、2 つ目の例はエラーとなったのです:

    ts
    // strictNullChecks: trueのとき
    type Array = {
    find(predicate: (value: any, index: number) => boolean): S | undefined;
    };
    // strictNullChecks: falseのとき、undefinedは型システムから取り除かれ、
    // 常に結果が見つかるかのようにコードを書けるようになります
    type Array = {
    find(predicate: (value: any, index: number) => boolean): S;
    };
    • Recommended
    • Default:

      true if strict; false otherwise.

    • Related:
    • Released:

      2.0

    # Strict Property Initialization - strictPropertyInitialization

    true に設定した場合、Class プロパティが宣言されているがコンストラクターで値がセットされていないときに、TypeScript はエラーを発生させます。

    ts
    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;
    // 注 this.emailがセットされていません
    }
    }
    Try

    上記の場合:

    • this.nameは具体的に設定されています。
    • this.accountTypeはデフォルト値が設定されています。
    • this.emailは値が設定されていないため、エラーとなります。
    • this.addressundefinedになりうる値として宣言されており、これは値の設定が必須でないことを意味しています。
    • Recommended
    • Default:

      true if strict; false otherwise.

    • Related:
    • Released:

      2.7

    # Use Unknown In Catch Variables - useUnknownInCatchVariables

    In TypeScript 4.0, support was added to allow changing the type of the variable in a catch clause from any to unknown. Allowing for code like:

    ts
    try {
    // ...
    } catch (err) {
    // We have to verify err is an
    // error before using it as one.
    if (err instanceof Error) {
    console.log(err.message);
    }
    }
    Try

    This pattern ensures that error handling code becomes more comprehensive because you cannot guarantee that the object being thrown is a Error subclass ahead of time. With the flag useUnknownInCatchVariables enabled, then you do not need the additional syntax (: unknown) nor a linter rule to try enforce this behavior.

    • Recommended
    • Default:

      true if strict; false otherwise.

    • Related:
    • Released:

      4.4

    #Modules

    # Allow Arbitrary Extensions - allowArbitraryExtensions

    In TypeScript 5.0, when an import path ends in an extension that isn’t a known JavaScript or TypeScript file extension, the compiler will look for a declaration file for that path in the form of {file basename}.d.{extension}.ts. For example, if you are using a CSS loader in a bundler project, you might want to write (or generate) declaration files for those stylesheets:

    css
    /* app.css */
    .cookie-banner {
    display: none;
    }
    ts
    // app.d.css.ts
    declare const css: {
    cookieBanner: string;
    };
    export default css;
    ts
    // App.tsx
    import styles from "./app.css";
    styles.cookieBanner; // string

    By default, this import will raise an error to let you know that TypeScript doesn’t understand this file type and your runtime might not support importing it. But if you’ve configured your runtime or bundler to handle it, you can suppress the error with the new --allowArbitraryExtensions compiler option.

    Note that historically, a similar effect has often been achievable by adding a declaration file named app.css.d.ts instead of app.d.css.ts - however, this just worked through Node’s require resolution rules for CommonJS. Strictly speaking, the former is interpreted as a declaration file for a JavaScript file named app.css.js. Because relative files imports need to include extensions in Node’s ESM support, TypeScript would error on our example in an ESM file under --moduleResolution node16 or nodenext.

    For more information, read up the proposal for this feature and its corresponding pull request.

      # Allow Importing TS Extensions - allowImportingTsExtensions

      --allowImportingTsExtensions allows TypeScript files to import each other with a TypeScript-specific extension like .ts, .mts, or .tsx.

      This flag is only allowed when --noEmit or --emitDeclarationOnly is enabled, since these import paths would not be resolvable at runtime in JavaScript output files. The expectation here is that your resolver (e.g. your bundler, a runtime, or some other tool) is going to make these imports between .ts files work.

        # Allow Umd Global Access - allowUmdGlobalAccess

        allowUmdGlobalAccessを true に設定すると、モジュールの内部から UMD へグローバルにアクセスできるようになります。モジュールファイルとは、import や export を使っているファイルのことです。このフラグを利用しない場合、UMD モジュールを利用するには import 宣言文が必要です。

        このフラグの利用例は、特定のライブラリ(jQuery や Lodash など)が常に実行時に利用可能であると分かっているが、import 文ではそのライブラリにアクセスできないような web プロジェクトです。

        # Base Url - baseUrl

        絶対パス参照でないモジュール名を解決するための基点となるディレクトリを設定できます。

        絶対パスで解決するために、ルートフォルダを決めることもできます。すなわち、

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

        "baseUrl": "./"とすると、このプロジェクト内では、TypeScript はtsconfig.jsonと同じフォルダからファイルの探索を行います。

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

        "../""./"のような毎度のインポート文にうんざりしていたり、 ファイルを移動するときにインポート文を変更する必要がある場合、このオプションは修正するための良い方法です。

          # Custom Conditions - customConditions

          --customConditions takes a list of additional conditions that should succeed when TypeScript resolves from an exports or imports field of a package.json. These conditions are added to whatever existing conditions a resolver will use by default.

          For example, when this field is set in a tsconfig.json as so:

          jsonc
          {
          "compilerOptions": {
          "target": "es2022",
          "moduleResolution": "bundler",
          "customConditions": ["my-condition"]
          }
          }

          Any time an exports or imports field is referenced in package.json, TypeScript will consider conditions called my-condition.

          So when importing from a package with the following package.json

          jsonc
          {
          // ...
          "exports": {
          ".": {
          "my-condition": "./foo.mjs",
          "node": "./bar.mjs",
          "import": "./baz.mjs",
          "require": "./biz.mjs"
          }
          }
          }

          TypeScript will try to look for files corresponding to foo.mjs.

          This field is only valid under the node16, nodenext, and bundler options for --moduleResolution.

          # Module - module

          より詳細については、ハンドブックのModulesの章を参照してください。おそらく"CommonJS"が求められるでしょう。

          次のファイルに対する出力の例をいくつか示します:

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

          CommonJS

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

          ts
          (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

          ts
          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

          ts
          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 / ES2020

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

          # Module Resolution - moduleResolution

          モジュール解決の方法を’node’(Node.js)または’classic’(TypeScript pre-1.6)から設定します。おそらく利用する必要はないでしょう。

          # Module Suffixes - moduleSuffixes

          Provides a way to override the default list of file name suffixes to search when resolving a module.

          {
          "moduleSuffixes": [".ios", ".native", ""]
          }
          }

          Given the above configuration, an import like the following:

          ts
          import * as foo from "./foo";

          TypeScript will look for the relative files ./foo.ios.ts, ./foo.native.ts, and finally ./foo.ts.

          Note the empty string "" in moduleSuffixes which is necessary for TypeScript to also look-up ./foo.ts.

          This feature can be useful for React Native projects where each target platform can use a separate tsconfig.json with differing moduleSuffixes.

          # No Resolve - noResolve

          デフォルトでは、TypeScript は起動時に与えられたファイルについてimport<referenceディレクティブを確認し、解決されたファイルをプログラムに追加します。

          noResolveが設定されているとき、このプロセスは発生しなくなります。 しかし、import文は正しいモジュールを解決しているかどうかチェックされるため、これが満たされているかどうかを他の方法で確認する必要があります。

            # Paths - paths

            baseUrlからの相対的な検索場所にインポートを再マッピングするエントリです。pathsについてより網羅的な記述はハンドブックに記載されています。

            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 に対して、ファイルリゾルバーへコードを見つけるためのカスタムプレフィクスによる補助をさせています。 このパターンは、コードベース内で長い相対パスを避けるために利用できます。

              # Resolve JSON Module - resolveJsonModule

              ‘.json’拡張子のファイルをモジュールとしてインポートできるようにします。Node のプロジェクトで一般的に利用されている手法です。 このオプションは、import時に静的な JSON の構造から型を生成します。

              デフォルトでは、TypeScript は JSON ファイルの解決をサポートしていません:

              ts
              // @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

              このオプションを有効にすると JSON のインポートが可能となり、JSON ファイルの型を検査できるようになります。

              ts
              // @filename: settings.json
              {
              "repo": "TypeScript",
              "dry": false,
              This comparison appears to be unintentional because the types 'boolean' and 'number' have no overlap.2367This comparison appears to be unintentional because 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

                # Resolve package.json Exports - resolvePackageJsonExports

                --resolvePackageJsonExports forces TypeScript to consult the exports field of package.json files if it ever reads from a package in node_modules.

                This option defaults to true under the node16, nodenext, and bundler options for --moduleResolution.

                # Resolve package.json Imports - resolvePackageJsonImports

                --resolvePackageJsonImports forces TypeScript to consult the imports field of package.json files when performing a lookup that starts with # from a file whose ancestor directory contains a package.json.

                This option defaults to true under the node16, nodenext, and bundler options for --moduleResolution.

                # Root Dir - rootDir

                デフォルト値: 型定義ファイルでないすべての入力ファイルの中での最長の共通パス。compositeが設定されている場合、この値の代わりにtsconfig.jsonを含むディレクトリがデフォルトとなります。

                TypeScript はファイルをコンパイルするとき、入力ディレクトリ内のディレクトリ構造が同じになるように出力ディレクト内の構造を保ちます。

                例えば、いくつかの入力ファイルがあったとしましょう:

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

                推定されるrootDirの値は、型定義ファイルでないすべての入力ファイルの中での最長の共通パス、この例ではcore/となります。

                outDirdistだったとすると、TypeScript は次のツリー構造を出力します:

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

                ただし、出力ディレクトリ内にcoreを含めることを意図している場合があります。 rootDir: "."tsconfig.jsonに設定すると、TypeScript は次のツリー構造を出力します:

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

                重要なこととして、rootDirどのファイルがコンパイルに含められるかに影響しませんtsconfig.jsonincludeexcludefiles設定との相互作用はありません。

                TypeScript はoutDir以外のディレクトリに出力ファイルを書き込むことはなく、ファイルの入力をスキップすることもありません。 このため、rootDirは出力する必要があるすべてのファイルが rootDir パスの下にあることを強制します。

                例えば、次のツリー構造があったとしましょう:

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

                rootDircoreに、include*に設定すると、outDir外部(i.e. ../helpers.ts)に出力する必要のあるファイル(helpers.ts)が生まれるため、エラーとなります。

                • Default:

                  Computed from the list of input files.

                • Released:

                  1.5

                # Root Dirs - rootDirs

                rootDirsを用いると、単一のルートとして振る舞う「仮想的な」ディレクトリが複数存在することをコンパイラへ伝えることができます。

                「仮想的な」ディレクトリは 1 つにまとめられるとしても、この設定によって、コンパイラはこれらのディレクトリ内での相対パスによるモジュールのインポートを解決できるようになります。

                例えば:

                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"]
                }
                }

                この設定は TypeScript がどのように JavaScript を出力するかには影響しません。 実行時に相対パスを使って動作可能であるという仮定がエミュレートされるだけです。

                • Default:

                  Computed from the list of input files.

                • Released:

                  2.0

                # Type Roots - typeRoots

                デフォルトでは、表示されているすべての”@types“パッケージがコンパイル時にインクルードされます。 プロジェクトを囲んでいる任意のフォルダのnode_modules/@types内のパッケージが表示されているとみなされます。 例えば、./node_modules/@types/../node_modules/@types/../../node_modules/@types/に存在するパッケージが該当します。

                typeRootsを設定すると、typeRoots配下のパッケージのみがインクルードされます。例えば:

                json
                {
                "compilerOptions": {
                "typeRoots": ["./typings", "./vendor/types"]
                }
                }

                この設定ファイルは、./typings./vendor/types以下のすべてのパッケージがインクルードされ、./node_modules/@typesのパッケージはインクルードされません。 パスはすべて、tsconfig.jsonからの相対パスです。

                # Types - types

                デフォルトでは、すべての表示されている@types“パッケージがコンパイル時にインクルードされます。 プロジェクトを囲んでいる任意のフォルダのnode_modules/@types内のパッケージが表示されているとみなされます。 例えば、./node_modules/@types/../node_modules/@types/../../node_modules/@types/に存在するパッケージが該当します。

                typesを設定すると、リストに列挙したパッケージのみがインクルードされます。例えば:

                json
                {
                "compilerOptions": {
                "types": ["node", "lodash", "express"]
                }
                }

                このtsconfig.jsonファイルは、./node_modules/@types/node./node_modules/@types/lodash./node_modules/@types/expressのみをインクルードするようになります。 node_modules/@types/*配下にある他のパケージはインクルードされません。

                この機能はtypeRootsと違い、インクルードしたい types パッケージだけを厳密に指定できます。一方、typeRootsは必要としている特定のフォルダを指定できます。

                #Emit

                # Declaration - declaration

                プロジェクト内のすべての TypeScript ファイルと JavaScript ファイルについて、d.tsファイルを生成します。 生成されたd.tsファイルはモジュールの外部 API を記述する定義ファイルです。 d.tsファイルを用いると、TypeScript などのツールは、型指定されていないコードに対して、Intelisence や正確な型定義を提供できるようになります。

                declarationtrueに設定している場合、次の TypeScript コードに対してコンパイラーを実行すると:

                ts
                export let helloWorld = "hi";
                Try

                次のようなindex.jsファイルが生成されます:

                ts
                export let helloWorld = "hi";
                 
                Try

                対応するhelloWorld.d.tsファイルは次のとおりです:

                ts
                export declare let helloWorld: string;
                 
                Try

                JavaScript ファイルに対応する.d.tsを利用する場合、emitDeclarationOnlyoutDirを設定することで JavaScript ファイルを上書きしないようにできます。

                # Declaration Dir - declarationDir

                型定義ファイルが出力されるルートディレクトリを設定します。

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

                次のtsconfig.jsonは:

                {
                "": true,
                "": "./types"
                }
                }

                index.tsに対応する d.ts ファイルをtypesフォルダへ配置します:

                example ├── index.js ├── index.ts ├── package.json ├── tsconfig.json └── types └── index.d.ts

                # Declaration Map - declarationMap

                元の.tsソースファイルにマップされる.d.tsのソースマップを生成します。

                これにより、VS Code などのエディターは、Go to Definitionのような機能で元の.tsファイルにジャンプできるようになります。

                プエジェクト参照機能を利用している場合、このオプションの有効化を強く推奨します。

                # Downlevel Iteration - downlevelIteration

                ダウンレベル化は、古いバージョンの JavaScript にトランスパイルするという意味の TypeScript の用語です。 このフラグは、モダンな JavaScript における新しいコンセプトの反復処理が古い JavaScript での実行時にどのように実装されるかについて、より正確なサポートを有効化します。

                ECMAScript 6 では、いくつかの新しい反復処理のための基本構文が加えられました: for / ofループ(for (el of arr))、配列のスプレッド([a, ...b])、引数のスプレッド(fn(...args))、Symbol.iteratorです。 --downlevelIterationは、Symbol.iteratorの実装が存在している場合、ES5 環境におけるこれらの基本的な反復処理をより正確に利用可能になります。

                例: for / ofでの効果

                downlevelIterationが無効であるとき、任意のオブジェクトに対するfor / ofループは旧来のforループへダウンレベルトランスパイルされます:

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

                これは大概の場合で期待通りの結果となりますが、ECMAScript 6 の挙動と 100%合致しているわけではありません。 特定の文字列、たとえば絵文字(😜)は、.lengthは 2(もしくはそれ以上!)ですが、for-ofループでは 1 文字分として反復されねばなりません。 より詳細な解説はJonathan New による blogを参照してください。

                downlevelIterationが有効であるとき、TypeScript はSymbol.iteratorの実装(ネイティブまたはポリフィル)をチェックするヘルパー関数を利用します。 もし実装が存在しなければ、index を利用する反復処理へフォールバックします。

                ts
                "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: Symbol.iteratorが実行時に存在しない場合、downlevelIterationは ECMAScript への準拠を保証しません。

                例: 配列のスプレッドに対する効果

                次のスプレッドされた配列について:

                js
                // 要素が1で、その後にarr2の要素が続く新しい配列を作成します
                const arr = [1, ...arr2];

                説明に沿って、次のように ES5 へダウンレベル化できます:

                js
                // 同じですよね?
                const arr = [1].concat(arr2);

                しかし、これは特定の稀なケースにおいてはっきりとした違いがあります。 例えば、配列に「穴」がある場合、スプレッドでは欠落したインデックスが独自のプロパティとして作成されますが、concatを利用した場合は作成されません:

                js
                // 「1」の要素が欠落している配列を作成します
                let missing = [0, , 1];
                let spreaded = [...missing];
                let concated = [].concat(missing);
                // true
                "1" in spreaded;
                // false
                "1" in concated;

                for / ofと同様、downlevelIterationは(利用可能であれば)Symbol.iteratorを使い、より正確に ES6 の挙動を模倣します。

                # Emit BOM - emitBOM

                TypeScript がファイルを書き込むときにバイトオーダーマーク(BOM)を出力するかどうかを制御します。 一部の実行環境では JavaScript ファイルを正しく解釈するために、BOM が必要となりますが、他の実行環境では BOM の存在を許容しません。 デフォルト値のfalseは一般的に最適な値ですが、必要であれば変更できます。

                  # Emit Declaration Only - emitDeclarationOnly

                  .d.tsファイルのみを出力します; .jsファイルは出力しません。

                  この設定は 2 つのケースで有用です:

                  • JavaScript を生成するために、TypeScript 以外のトランスパイラを使っているとき
                  • 利用者向けにd.tsファイルを出力するためだけに TypeScript を使っているとき

                  # Import Helpers - importHelpers

                  Class の継承、配列やオブジェクトのスプレッド構文、async の処理など、特定のダウンレベル処理に対して、TypeScript はヘルパーコードを利用します。 デフォルトでは、ヘルパーは利用されているファイルに挿入されます。 同じヘルパーが異なる多くのモジュールで利用されている場合、コードの重複となる可能性があります。

                  importHelpersフラグが有効な場合、ヘルパー関数はtslibモジュールからインポートされます。 tslibを実行時にインポート可能であることを確認する必要があります。 この設定はモジュールに作用します。グローバルなスクリプトファイルはモジュールをインポートしません。

                  例えば、次の TypeScript について:

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

                  downlevelIterationimportHelpersが false のときは次の出力となります:

                  ts
                  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, pack) {
                  if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
                  if (ar || !(i in from)) {
                  if (!ar) ar = Array.prototype.slice.call(from, 0, i);
                  ar[i] = from[i];
                  }
                  }
                  return to.concat(ar || Array.prototype.slice.call(from));
                  };
                  export function fn(arr) {
                  var arr2 = __spreadArray([1], __read(arr), false);
                  }
                   
                  Try

                  downlevelIterationimportHelpersの両方を有効化すると、次の出力になります:

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

                  これらのヘルパー関数の独自実装を与える場合、noEmitHelpersが利用できます。

                  # Imports Not Used As Values - importsNotUsedAsValues

                  このフラグはimportがどのように動作するかを制御します。3 つの異なるオプションがあります:

                  • remove: 型のみを参照するimport文を削除するデフォルトの挙動

                  • preserve: 使用されない値または型のすべてのimport文を保持します。これにより、インポート/副作用が保持されます。

                  • error: すべての import を保持しますが(preserve オプションと同じ)、値の import が型としてのみ使用されている場合にエラーを出力します。これは、誤って値が import されないようにしつつ、副作用のある import を明示的にしたい場合に有用です。

                  このフラグが機能することで、import typeを使用して、JavaScript に出力されないimport文を明示的に作成できます。

                  # Inline Source Map - inlineSourceMap

                  設定すると、TypeScript はソースマップを.js.mapファイルへ出力するのではなく、ソースマップの内容を.jsファイルに埋め込みます。 この結果、JS ファイルはより大きくなりますが、いくつかのシナリオにおいては便利です。 例えば、.mapファイルの提供が許可されていない web サーバーで JS ファイルをデバッグしたい、という場合です。

                  このオプションは、sourceMapとは互いに排他的にです。

                  例えば、次の TypeScript は:

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

                  次の JavaScript に変換されます:

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

                  inlineSourceMapを有効にしてビルドすると、 ファイルの末尾にこのファイルのソースマップを含んだコメントが出力されます。

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

                  # Inline Sources - inlineSources

                  設定すると、TypeScript は元の.tsファイルの内容を文字列としてソースマップに埋め込みます。 このオプションはinlineSourceMapと同様のケースで有用です。

                  sourceMapまたはinlineSourceMapのいずれかが設定されている必要があります。

                  例えば、次の TypeScript について:

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

                  デフォルトでは、次の JavaScript に変換されます:

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

                  inlineSourcesinlineSourceMapを有効にしてビルドすると、 ファイルの末尾にこのファイルのソースマップを含んだコメントが付きます。 このソースマップは元となったソースコードも含んでいるため、inlineSourceMapの例とは異なる点に留意してください。

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

                  # Map Root - mapRoot

                  生成された場所情報を利用するのではなく、デバッガがマップファイルを探索すべき場所を明示します。 この文字列はソースマップの中で、文字列そのままの値として処理されます。例えば:

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

                  この設定は、index.jshttps://my-website.com/debug/sourcemaps/index.js.mapにソースマップがあることを宣言しています。

                    # New Line - newLine

                    ファイルを出力するときの改行コードを指定します: ‘CRLF’(dos)または’LF’(unix)のいずれかを指定してください。

                    • Default:

                      Platform specific.

                    • Allowed:
                      • crlf

                      • lf

                    • Released:

                      1.5

                    # No Emit - noEmit

                    JavaScript ソースコード、ソースマップ、型定義のファイルを出力しないようにします。

                    これにより、Babelswcなどの TypeScript ファイルを JavaScript 環境内で実行可能なファイルへ変換するための別のツールを追加できます。

                    TypeScript をエディター統合やソースコードの型チェックツールとして利用できるようになります。

                      # No Emit Helpers - noEmitHelpers

                      importHelpersを使って、ヘルパ関数をインポートする代わりに、グローバルスコープに使用するヘルパ関数のための実装を提供し、ヘルパ関数が出力されるのを完全に無効にできます。

                      例えば、このasync関数を ES5 で実行するためには、awaitのような関数とgeneratorのような関数が必要です:

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

                      これは、とても多くの JavaScript を生成します:

                      ts
                      "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 (g && (g = 0, op[0] && (_ = 0)), _) 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

                      このフラグを通じて、独自のグローバル実装に切り替えられます:

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

                      エラーがあるときに、JavaScript ソースコードやソースマップファイル、型定義ファイルなどをコンパイラに出力させないようにします。

                      デフォルト値はfalseであり、このため、すべてのエラーを解決するよりも前に別の環境でコードの変更結果を確認したいといったファイル監視環境において、TypeScript が扱いやすくなっています。

                      # Out Dir - outDir

                      設定すると、.jsファイル(.d.ts.js.mapファイルも同様)がこのディレクトリ内に出力されます。 元のソースファイルのディレクトリ構造は保存されます。結果のルート構造が意図どおりでない場合は、rootDirを参照してください。

                      設定しない場合、.jsファイルは.tsファイルを作成したのと同じディレクトリに出力されます。

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

                      次のようなtsconfig.jsonの場合:

                      json
                      {
                      "compilerOptions": {
                      "outDir": "dist"
                      }
                      }

                      この設定でtscを実行すると、ファイルは指定されたdistフォルダに生成されます。

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

                      # Out File - outFile

                      設定すると、すべてのグローバルな(モジュールでない)ファイルは指定した単一の出力ファイルに結合されます。

                      もしmodulesystemamdの場合、この単一出力ファイルのグローバルなコンテンツの後ろにすべてのモジュールファイルも結合されます。

                      Note: moduleNoneSystemAMDのいずれかでない限り、outFileは使用できません。 このオプションは CommonJS または ES6 Modules にバンドルする目的では使用できません

                      # Preserve Const Enums - preserveConstEnums

                      コード生成時にconst enumの定義を取り除かないようにします。 const enumは、参照ではなく Enum 値を出力することによって、アプリケーション実行時の全体的なメモリの使用量を軽減します。

                      例えば次の TypeScript では:

                      ts
                      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

                      デフォルトのconst enumの挙動は、すべてのAlbum.Somethingを対応する数値リテラル値に変換し、 JavaScript コードから完全に元の Enum への参照を除去します。

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

                      preserveConstEnumstrueに設定すると、enumは実行時に残り、数値も出力されるようになります。

                      ts
                      "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 /* Album.JimmyEatWorldFutures */;
                      if (selectedAlbum === 1 /* Album.JimmyEatWorldFutures */) {
                      console.log("That is a great choice.");
                      }
                       
                      Try

                      このオプションによって、このようなconst enumsは実行時に追跡されないソースコードのみの機能になります。

                      # Preserve Value Imports - preserveValueImports

                      Deprecated in favor of verbatimModuleSyntax.

                      There are some cases where TypeScript can’t detect that you’re using an import. For example, take the following code:

                      ts
                      import { Animal } from "./animal.js";
                      eval("console.log(new Animal().isDangerous())");

                      or code using ‘Compiles to HTML’ languages like Svelte or Vue. preserveValueImports will prevent TypeScript from removing the import, even if it appears unused.

                      When combined with isolatedModules: imported types must be marked as type-only because compilers that process single files at a time have no way of knowing whether imports are values that appear unused, or a type that must be removed in order to avoid a runtime crash.

                      # Remove Comments - removeComments

                      TypeScript ファイルを JavaScript へ変換するときに、すべてのコメントを除去します。デフォルト値はfalseです。

                      例えば、次の JSDoc コメントを持つ TypeScript ファイルに対して:

                      ts
                      /** ポルトガル語に翻訳された'Hello world' */
                      export const helloWorldPTBR = "Olá Mundo";

                      removeCommentstrueであるとき、次のようになります:

                      ts
                      export const helloWorldPTBR = "Olá Mundo";
                       
                      Try

                      removeCommentsが設定されていない・またはfalseであるときは次のようになります:

                      ts
                      /** ポルトガル語に翻訳された'Hello world' */
                      export const helloWorldPTBR = "Olá Mundo";
                       
                      Try

                      つまり、コメントは JavaScript コードに表示されるようになります。

                        # Source Map - sourceMap

                        ソースマップファイルの生成を有効化します。 これらのファイルにより、出力された JavaScript ファイルが実際に動作させるときに、デバッガーやその他のツールが元の TypeScript ソースファイルを表示できるようになります。 ソースマップファイルは.js.map(または.jsx.map)として、対応する.jsファイルとともに出力されます。

                        次の例のように、.jsファイルには、外部ツールにソースマップファイルがどこにあるかを示すためのソースマップコメントが含まれるようになります:

                        ts
                        // helloWorld.ts
                        export declare const helloWorld = "hi";

                        sourceMaptrueに設定してコンパイルすると、次の JavaScript ファイルが生成されます:

                        js
                        // helloWorld.js
                        "use strict";
                        Object.defineProperty(exports, "__esModule", { value: true });
                        exports.helloWorld = "hi";
                        //# sourceMappingURL=// helloWorld.js.map

                        この設定は次のような json 形式のマップファイルも生成します:

                        json
                        // helloWorld.js.map
                        {
                        "version": 3,
                        "file": "ex.js",
                        "sourceRoot": "",
                        "sources": ["../ex.ts"],
                        "names": [],
                        "mappings": ";;AAAa,QAAA,UAAU,GAAG,IAAI,CAAA"
                        }

                          # Source Root - sourceRoot

                          相対的なソースコードの場所の代わりに、デバッガが TypeScript のファイルを探索すべき場所を明示します。 この文字列は、パスや URL を使用できるソースマップの中で、文字列そのままの値として処理されます:

                          json
                          {
                          "compilerOptions": {
                          "sourceMap": true,
                          "sourceRoot": "https://my-website.com/debug/source/"
                          }
                          }

                          上記の設定は、index.jshttps://my-website.com/debug/source/index.tsにソースコードがある、ということを宣言しています。

                            # Strip Internal - stripInternal

                            JSDoc コメントとして@internalが付与されたコードについて、定義情報を出力しないようにします。 このオプションはコンパイラが内部で利用するためのものです; コンパイラは結果の妥当性検証をしないため、自己責任で使ってください。 d.tsファイル内での可視性を細かく制御できるツールを探しているのであれば、api-extractorを参照してください。

                            ts
                            /**
                            * 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

                            このフラグがfalseであるとき(デフォルト):

                            ts
                            /**
                            * 一週間の日数
                            * @internal
                            */
                            export declare const daysInAWeek = 7;
                            /** 一週間あたりの稼ぎを計算する */
                            export declare function weeklySalary(dayRate: number): number;
                             
                            Try

                            stripInternaltrueに設定すると、d.tsは次のように編集されて出力されます。

                            ts
                            /** 一週間あたりの稼ぎを計算する */
                            export declare function weeklySalary(dayRate: number): number;
                             
                            Try

                            JavaScript としての出力は一緒です。

                            • Internal

                            #JavaScript Support

                            # Allow JS - allowJs

                            .ts.tsxファイルだけでなく、JavaScript ファイルをプロジェクトへインポートできるようにします。例えば、次の JS ファイルを:

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

                            TypeScript のファイルへインポートするとエラーとなるでしょう:

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

                            allowJsを付与するとインポートは成功します:

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

                            このフラグを使うと、.ts.tsxファイルが既存の JavaScript ファイルと共存可能となり、TypeScript ファイルを JS プロジェクトへ徐々に追加できるようになります。

                            # Check JS - checkJs

                            allowJsと連携動作します。checkJsが有効化されている場合、JavaScript ファイル内のエラーが報告されるようになります。 これは、プロジェクトに含まれるすべての JavaScript ファイルの先頭で// @ts-checkを付与することと等価です。

                            例えば、TypeScript のparseFloat定義から、次の例は誤った JavaScript です。

                            js
                            // parseFloatはstringのみを受け付けます
                            module.exports.pi = parseFloat(3.124);

                            このファイルが TypeScript のモジュールにインポートされた場合:

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

                            いかなるエラーも報告されません。しかし、もしcheckJsを有効化すれば、JavaScript ファイルで発生したエラーメッセージを受け取れるようになります。

                            ts
                            // @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

                            # Max Node Module JS Depth - maxNodeModuleJsDepth

                            node_modules配下で依存関係を探す際や、JavaScript ファイルをロードする際の最大の深さです。

                            このフラグはallowJsが有効化されているときのみ利用可能であり、node_modules内のすべての JavaScript について、TypeScript に型推論させたいときに用います。

                            理想的には、このオプションの値は 0(デフォルト値)であるべきで、d.tsファイルでモジュールを明示的に定義すべきです。 ただし、速度と精度を犠牲にして、このオプションを有効化したいという場合もあるかもしれません。

                              #Editor Support

                              # Disable Size Limit - disableSizeLimit

                              非常に大規模な JavaScript プロジェクトで作業するときに発生する可能性のある使用メモリの膨張を避けるために、TypeScript が割り当てられるメモリの量には上限があります。このフラグを設定すると、この制限を取り除きます。

                                # Plugins - plugins

                                エディタ内部で動作させる Language Service のプラグインを列挙します。

                                Language Service プラグインを用いることで、ユーザーは TypeScript ファイルから追加情報を受け取ることができます。プラグインは、TypeScript とエディタ間でやりとりされているメッセージを拡張したり、プラグイン独自エラーメッセージを提供できます。

                                例:

                                • ts-sql-plugin — テンプレート文字列による SQL ビルダについて、SQL の構文チェックを追加します。
                                • typescript-styled-plugin — テンプレート文字列内部の CSS を構文チェック機能を提供します。
                                • typescript-eslint-language-service — eslint のエラーメッセージを出力や、出力されたエラーメッセージの修正機能を提供します。
                                • ts-graphql-plugin — テンプレート文字列内部の GraphQL クエリについて、バリデーションと自動補完機能を提供します。

                                VS Code には、拡張のためのLnguage Service プラグインの自動読込 機能があるため、tsconfig.jsonにプラグインの定義を書かずにエディタ上でプラグインを動作させることもできます。

                                  #Interop Constraints

                                  # Allow Synthetic Default Imports - allowSyntheticDefaultImports

                                  allowSyntheticDefaultImportsを true に設定すると、次のようなインポートが可能になります:

                                  ts
                                  import React from "react";

                                  下記のようにする必要はありません:

                                  ts
                                  import * as React from "react";

                                  モジュールが default export を指定していなくても利用可能です。

                                  このオプションは TypeScript が出力する JavaScript へは影響しません。型チェックにのみ影響があります。 このオプションにより、モジュールの default export を自然に扱えるようにする追加コードが出力されている環境では、TypeScript と Babel の挙動が揃います。

                                  # ES Module Interop - esModuleInterop

                                  すべてのインポートに対して Namespace オブジェクトを生成することによって、CommonJS と ES Modules 間で相互運用可能なコードを出力します。

                                  TypeScript は EcmaScript のモジュール標準に準拠しています。 つまり、import React from "react"のような構文をサポートするには、そのファイルに具体的なdefault export が含まれている必要があります。 CommonJS のモジュールでは、このエクスポートの方法は稀です。esModuleInteropが true でなければ:

                                  ts
                                  // @filename: utilFunctions.js
                                  const getStringLength = (str) => str.length;
                                   
                                  module.exports = {
                                  getStringLength,
                                  };
                                   
                                  // @filename: index.ts
                                  import utils from "./utilFunctions";
                                   
                                  const count = utils.getStringLength("Check JS");
                                  Try

                                  インポート可能なオブジェクトにdefaultが無いため、このコードは動作しないでしょう。このコードが動作するように見えたとしても、です。 Babel のようなトランスパイラは、利便のために default が存在しない場合に自動で作成します。モジュールを次のようにするのです:

                                  js
                                  // @filename: utilFunctions.js
                                  const getStringLength = (str) => str.length;
                                  const allFunctions = {
                                  getStringLength,
                                  };
                                  module.exports = allFunctions;

                                  このコンパイラフラグを有効化すると、allowSyntheticDefaultImportsも有効化されます。

                                  # Force Consistent Casing In File Names - forceConsistentCasingInFileNames

                                  TypeScript が大文字小文字を区別するかどうかは、動作しているファイルシステムに従います。 これが問題になるのは、ある開発者はケースセンシティブなファイルシステムで作業をしている一方で、別の開発者はそうではない場合です。 あるファイルがfileManager.tsの Import を./FileManager.tsと指定したとき、ケースセンシティブでないファイルシステムではファイルが見つかりますが、ケースセンシティブなファイルシステムでは見つかりません。

                                  このオプションを有効化すると、TypeScript はプログラムがディスク上の大文字小文字と異なるファイルをインクルードしようとした場合にエラーを発生させます。

                                  • Recommended
                                  • Default:

                                    true

                                  # Isolated Modules - isolatedModules

                                  TypeScript を TypeScript コードから JavaScript コードを生成する用途で利用可能な一方、Babelなどの他のトランスパイラの利用も一般的です。 しかし、他のトランスパイラは一度に1ファイルのみを扱うため、全体の型システムの知識に依存したコード変換はできません。 ビルドツールで用いられる TypeScript のts.transpileModuleAPI についても、この制約が課せられます。

                                  この制限は、TypeScript のconst enumnamespaceのような機能を利用したときに実行時の問題を引き起こします。 isolatedModulesフラグは、単一ファイルのトランスパイル処理で正しく解釈できないコードが書かれたときに、TypeScript が警告を与えるように設定します。

                                  このフラグは、コードの挙動を変更せず、また、TypeScript のチェック・出力プロセスの挙動も変更しません。

                                  isolatedModulesが有効な場合に機能しないコードをいくつか例示します。

                                  値でない識別子のエクスポート

                                  TypeScript では、をインポートしてからエクスポートできます:

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

                                  someTypeという値は存在しないため、出力されたexport文はエクスポートを試行しません(これは JavaScript の実行時エラーになります):

                                  js
                                  export { someFunction };

                                  単一ファイルのトランスパイラは、someTypeが値なのかどうかを知らないため、型のみを参照した名前をエクスポートするエラーになります。

                                  Module でないファイル

                                  isolatedModulesが設定されている場合、すべての実装ファイルはModuleでなくてはなりません(import/exportの形式を利用しているという意味)。ファイルが Module でない場合、エラーが発生します。

                                  ts
                                  function fn() {}
                                  Try

                                  この制約は.d.tsファイルには適用されません。

                                  const enumメンバーへの参照

                                  TypeScript では、const enumのメンバへ参照すると、出力される JavaScript では、その参照は実際の値へと置換されます。TypeScript による変換は次のようになります:

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

                                  JavaScript では:

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

                                  他のトランスパイラはメンバー値の知識無しにNumbersへの参照を置換できません。これが取り残されると、実行時のエラーとなります(なぜならNumbersオブジェクトは実行時に存在しないからです)。 したがって、isolatedModulesが設定されている場合、const enumメンバーへのアンビエント参照はエラーとなります。

                                    シンボリックリンクを実体パスへ解決しないという Node.js の同名フラグを反映したオプションです。

                                    このフラグは Webpack のresolve.symlinksオプションと逆の動作をします(つまり、TypeScript のpreserveSymlinksを true に設定することは、Webpack のresolve.symlinksを false に設定することと同等です。逆も然りです)。

                                    このオプションを有効化すると、モジュールとパッケージへの参照(例えば、import/// <reference type="..." /> ディレクティブ)は、シンボリックリンクが解決する場所としてではなく、そのシンボリックリンクファイルからの相対パスとして解決されます。

                                      # Verbatim Module Syntax - verbatimModuleSyntax

                                      By default, TypeScript does something called import elision. Basically, if you write something like

                                      ts
                                      import { Car } from "./car";
                                      export function drive(car: Car) {
                                      // ...
                                      }

                                      TypeScript detects that you’re only using an import for types and drops the import entirely. Your output JavaScript might look something like this:

                                      js
                                      export function drive(car) {
                                      // ...
                                      }

                                      Most of the time this is good, because if Car isn’t a value that’s exported from ./car, we’ll get a runtime error.

                                      But it does add a layer of complexity for certain edge cases. For example, notice there’s no statement like import "./car"; - the import was dropped entirely. That actually makes a difference for modules that have side-effects or not.

                                      TypeScript’s emit strategy for JavaScript also has another few layers of complexity - import elision isn’t always just driven by how an import is used - it often consults how a value is declared as well. So it’s not always clear whether code like the following

                                      ts
                                      export { Car } from "./car";

                                      should be preserved or dropped. If Car is declared with something like a class, then it can be preserved in the resulting JavaScript file. But if Car is only declared as a type alias or interface, then the JavaScript file shouldn’t export Car at all.

                                      While TypeScript might be able to make these emit decisions based on information from across files, not every compiler can.

                                      The type modifier on imports and exports helps with these situations a bit. We can make it explicit whether an import or export is only being used for type analysis, and can be dropped entirely in JavaScript files by using the type modifier.

                                      ts
                                      // This statement can be dropped entirely in JS output
                                      import type * as car from "./car";
                                      // The named import/export 'Car' can be dropped in JS output
                                      import { type Car } from "./car";
                                      export { type Car } from "./car";

                                      type modifiers are not quite useful on their own - by default, module elision will still drop imports, and nothing forces you to make the distinction between type and plain imports and exports. So TypeScript has the flag --importsNotUsedAsValues to make sure you use the type modifier, --preserveValueImports to prevent some module elision behavior, and --isolatedModules to make sure that your TypeScript code works across different compilers. Unfortunately, understanding the fine details of those 3 flags is hard, and there are still some edge cases with unexpected behavior.

                                      TypeScript 5.0 introduces a new option called --verbatimModuleSyntax to simplify the situation. The rules are much simpler - any imports or exports without a type modifier are left around. Anything that uses the type modifier is dropped entirely.

                                      ts
                                      // Erased away entirely.
                                      import type { A } from "a";
                                      // Rewritten to 'import { b } from "bcd";'
                                      import { b, type c, type d } from "bcd";
                                      // Rewritten to 'import {} from "xyz";'
                                      import { type xyz } from "xyz";

                                      With this new option, what you see is what you get.

                                      That does have some implications when it comes to module interop though. Under this flag, ECMAScript imports and exports won’t be rewritten to require calls when your settings or file extension implied a different module system. Instead, you’ll get an error. If you need to emit code that uses require and module.exports, you’ll have to use TypeScript’s module syntax that predates ES2015:

                                      Input TypeScript Output JavaScript
                                      ts
                                      import foo = require("foo");
                                      js
                                      const foo = require("foo");
                                      ts
                                      function foo() {}
                                      function bar() {}
                                      function baz() {}
                                      export = {
                                      foo,
                                      bar,
                                      baz,
                                      };
                                      js
                                      function foo() {}
                                      function bar() {}
                                      function baz() {}
                                      module.exports = {
                                      foo,
                                      bar,
                                      baz,
                                      };

                                      While this is a limitation, it does help make some issues more obvious. For example, it’s very common to forget to set the type field in package.json under --module node16. As a result, developers would start writing CommonJS modules instead of an ES modules without realizing it, giving surprising lookup rules and JavaScript output. This new flag ensures that you’re intentional about the file type you’re using because the syntax is intentionally different.

                                      Because --verbatimModuleSyntax provides a more consistent story than --importsNotUsedAsValues and --preserveValueImports, those two existing flags are being deprecated in its favor.

                                      For more details, read up on the original pull request and its proposal issue.

                                        #Backwards Compatibility

                                        # Charset - charset

                                        以前の TypeScript のバージョンでは、このオプションでディスクからどのエンコードでファイルを読み込むかを制御していました。 今の TypeScript は UTF-8 でエンコードされていることを前提としています。ただし、UTF-16(BE および LE)または UTF-8 の BOM を正しく検出します。

                                        • Deprecated
                                        • Default:

                                          utf8

                                        # Keyof Strings Only - keyofStringsOnly

                                        このフラグは、 文字列インデックス記法の型として適用される際にkeyof型パラメータがstring | numberではなくstringを返すようにします。

                                        このフラグは、TypeScript 2.9 のリリースよりも前の挙動に保ちたいときに利用されます。

                                        • Deprecated
                                        • Released:

                                          2.9

                                        # No Implicit Use Strict - noImplicitUseStrict

                                        これは必要ないはずです。ES6 でないターゲットでモジュールを出力する際に、TypeScript はデフォルトで"use strict;"という前置きをファイルの一番始めに出力します。 この設定は、この前置きを無効にします。

                                          # No Strict Generic Checks - noStrictGenericChecks

                                          TypeScript は、総称型を使った 2 つの関数について、型パラメータを統合して比較します。

                                          ts
                                          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

                                          このフラグを利用することで、このチェックを無効化できます。

                                          # Out - out

                                          代わりにoutFileを使ってください。

                                          outオプションは、予測可能でない、または一貫性のない方法によってファイルの最終的な場所を計算してしまいます。 このオプションは後方互換性の維持のためにのみ残されていますが、非推奨です。

                                          # Suppress Excess Property Errors - suppressExcessPropertyErrors

                                          このオプションにより、次の例に示すような、プロパティが過剰に定義されているときのエラーを抑止します:

                                          ts
                                          type Point = { x: number; y: number };
                                          const p: Point = { x: 1, y: 3, m: 10 };
                                          Object literal may only specify known properties, and 'm' does not exist in type 'Point'.2353Object literal may only specify known properties, and 'm' does not exist in type 'Point'.
                                          Try

                                          このフラグは、TypeScript 1.6のオブジェクトリテラルの厳密チェックへの移行を助けるために追加されました。

                                          モダンなコードベースでの、このフラグの利用は推奨されません。エラー抑止が必要な箇所で、都度// @ts-ignoreを利用できます。

                                            # Suppress Implicit Any Index Errors - suppressImplicitAnyIndexErrors

                                            suppressImplicitAnyIndexErrorsを有効化すると、次の例に示すようなオブジェクトへインデックスアクセスしたときの暗黙的 any についてのエラーが抑止されます:

                                            ts
                                            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

                                            suppressImplicitAnyIndexErrorsはかなり影響の大きい方法です。代わりに@ts-ignoreコメントの利用を推奨します:

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

                                            #Language and Environment

                                            # Emit Decorator Metadata - emitDecoratorMetadata

                                            reflect-metadataモジュールとともに動作するデコレータのメタ情報を出力するための実験的なサポートを有効化します。

                                            例えば、次の JavaScript について、

                                            ts
                                            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

                                            emitDecoratorMetadataが true に設定されていない場合(デフォルト)、次のようになります:

                                            ts
                                            "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) {
                                            // 何もしない
                                            }
                                            }
                                            __decorate([
                                            LogMethod
                                            ], Demo.prototype, "foo", null);
                                            const demo = new Demo();
                                             
                                            Try

                                            emitDecoratorMetadataが true に設定されている場合は、次のようになります:

                                            ts
                                            "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) {
                                            // 何もしない
                                            }
                                            }
                                            __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

                                            デコレータの実験的なサポートを有効化します。 これは TC39 の標準化プロセスでは stage 2 の機能です。

                                            デコレータは JavaScript の仕様として、いまだ完全には組み込まれていない言語機能です。 これは TypeScript の実装バージョンが、TC39 が決定する JavaScript の実装と異なるかもしれないということを意味しています。

                                            TypeScript のデコレータのサポートについて、より詳しく知りたい場合はハンドブックを参照してください。

                                            # JSX - jsx

                                            JSX 構文がどのように JavaScript ファイルに出力されるかを設定します。 .tsxで終わるファイルの JS 出力にのみ影響します。

                                            • preserve: JSX を変更せずに.jsxファイルを出力します
                                            • react: JSX を等価なreact.createElementに変換して.jsファイルを出力します
                                            • react-native: JSX を変更せずに、.jsファイルを出力します

                                            # JSX Factory - jsxFactory

                                            JSX 要素がコンパイルされるときの.jsファイルで呼び出される関数を変更します。 preactを使う場合に、デフォルトの"React.createElement"の代わりに"h""preact.h"に変更するのが一般的な変更です。

                                            このオプションはBabel における/** @jsx h */ディレクティブと同じものです。

                                            # jsxFragmentFactory - jsxFragmentFactory

                                            コンパイラオプションにjsxFactoryが指定されており、React JSX のコンパイルを目的とする場合に使用される JSX フラグメントファクトリ関数(例: Fragment)を指定します。

                                            例えば、次の TSConfig では:

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

                                            この TSX ファイルは:

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

                                            次のようになります:

                                            tsx
                                            const preact_1 = require("preact");
                                            const HelloWorld = () => ((0, preact_1.h)(preact_1.Fragment, null,
                                            (0, preact_1.h)("div", null, "Hello")));
                                             
                                            Try

                                            このオプションはBabel の/* @jsxFrag h */ディレクティブとよく似ており、ファイル単位で使用できます。

                                            例:

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

                                            # jsxImportSource - jsxImportSource

                                            TypeScript 4.1 で導入された"react-jsx""react-jsxdev"jsxに指定する際にjsxjsxsのファクトリ関数をインポートするモジュール指定子を宣言します。

                                            React 17では、それぞれのインポートによる新しい JSX の変換がサポートされています。

                                            例えば、このコードで:

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

                                            次のような TSConfig の場合:

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

                                            TypeScript からコンパイルされる JavaScript は次のようになります:

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

                                            "jsxImportSource": "preact"を使用する場合、tsconfig は次のようになり:

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

                                            以下のようなコードが生成されます:

                                            tsx
                                            function App() {
                                            return (0, jsx_runtime_1.jsx)("h1", { children: "Hello World" });
                                            }
                                            exports.App = App;
                                             
                                            Try

                                            あるいは、ファイル単位のディレクティブを使ってこのオプションを設定することもできます。例えば:

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

                                            これにより、_jsxファクトリをインポートするpreact/jsx-runtimeが追加されます。

                                            注意: このオプションを期待通りに動作させるには、tsxファイルにexportまたはimportを含める必要があります。これにより、ファイルはモジュールとみなされます。

                                            # Lib - lib

                                            TypeScript には組み込みの JS API(例:Math)の型定義や、ブラウザーで利用される API(例:document)の型定義がデフォルトで組み込まれています。 指定したtargetに合致する新しい JS 機能の API の型定義も TypeScript には組み込まれています。例えば、Mapの定義はtargetES6かそれよりも新しいときに利用可能です。

                                            いくつかの理由により、これらを変更したい場合があります:

                                            • プログラムはブラウザーで動作させる必要がないため、"dom"の型定義が不要である
                                            • 利用している実行環境では特定の JavaScript API を提供しているが(Polyfill を利用しているかもしれません)、指定された ECMAScript のすべての構文をサポートしているわけではない
                                            • より上位の ECMAScript バージョンについて、すべてではなく、部分的な Polyfill や実装が利用可能である

                                            High Level libraries

                                            Name 内容
                                            ES5 ES3 と ES5 のすべての機能を利用するための型定義。
                                            ES2015 ES2015(ES6)で利用可能な API - array.findPromiseProxySymbolMapSetReflectなど。
                                            ES6 “ES2015”のエイリアス
                                            ES2016 ES2016 で利用可能な API - array.includeなど。
                                            ES7 “ES2016”のエイリアス
                                            ES2017 ES2017 で利用可能な API - Object.entriesObject.valuesAtomicsSharedArrayBufferdate.formatToParts、typed arrays など。
                                            ES2018 ES2018 で利用可能な API - async iterables、promise.finallyIntl.PluralRulesrexexp.groupsなど。
                                            ES2019 ES2019 で利用可能な API - array.flatarray.flatMapObject.fromEntriesstring.trimStartstring.trimEndなど。
                                            ES2020 ES2020 で利用可能な API - string.matchAllなど。
                                            ESNext ESNext で利用可能な API - JavaScript の仕様変遷によって内容は変化します。
                                            DOM DOMの型定義 - windowdocumentなど。
                                            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 source codeで読むことができます。

                                            # Module Detection - moduleDetection

                                            This setting controls how TypeScript determines whether a file is a script or a module.

                                            There are three choices:

                                            • "auto" (default) - TypeScript will not only look for import and export statements, but it will also check whether the "type" field in a package.json is set to "module" when running with module: nodenext or node16, and check whether the current file is a JSX file when running under jsx: react-jsx.

                                            • "legacy" - The same behavior as 4.6 and prior, usings import and export statements to determine whether a file is a module.

                                            • "force" - Ensures that every non-declaration file is treated as a module.

                                            • Default:

                                              "auto": Treat files with imports, exports, import.meta, jsx (with jsx: react-jsx), or esm format (with module: node16+) as modules.

                                            • Allowed:
                                              • legacy

                                              • auto

                                              • force

                                            • Released:

                                              4.7

                                            # No Lib - noLib

                                            すべてのライブラリファイルについて、自動でのインクルードを無効化します。 このオプションを設定した場合、libは無視されます。

                                            # React Namespace - reactNamespace

                                            代わりに--jsxFactoryを利用してください。reactのときに TSX ファイルのcreateElementが実行されるオブジェクトを指定します。

                                            • Default:

                                              React

                                            # Target - target

                                            モダンブラウザーはすべての ES6 機能をサポートしているため、ES6は良い選択です。 もし、コードをより古い環境へデプロイするのであれば、より下位の値を、逆により新しい環境での動作が保証される場合は、より上位の値をターゲットとして選択してください。

                                            target設定は、どの JS 機能が古い JavaScript 構文にトランスパイルされ、どの機能がそのまま残されるかを変更します。 例えばtargetが ES5 以下である場合、アロー関数() => thisは等価なfunction式へ変換されます。

                                            targetの変更はlibのデフォルト値も変更します。 必要に応じてtargetlibの値を組み合わせることも可能ですが、簡単にtargetの値のみを設定することも可能です。

                                            もし動作環境が Node.js のみであるならば、Node のベースバージョン毎に推奨されるtargetは次のとおりです:

                                            Name Supported Target
                                            Node 8 ES2017
                                            Node 10 ES2018
                                            Node 12 ES2019

                                            この表はnode.greenのデータベースを元に作成しています。

                                            ESNext という特別な値は TypeScript がサポートしている最新のターゲットバージョンを参照します。 この設定値は、異なる TypeScript のバージョン間におけるターゲットバージョンの一致を意味せず、アップグレード予測が困難になる可能性があるため、注意して利用する必要があります。

                                            • Default:

                                              ES3

                                            • Allowed:
                                              • es3

                                              • es5

                                              • es6/es2015

                                              • es2016

                                              • es2017

                                              • es2018

                                              • es2019

                                              • es2020

                                              • es2021

                                              • es2022

                                              • esnext

                                            • Released:

                                              1.0

                                            # Use Define For Class Fields - useDefineForClassFields

                                            このフラグは、最新の Class フィールドの仕様へ移行するために用います。TypeScript の Class フィールド記法は、TC39 が Class フィールドの仕様の合意に至るよりも何年も前に導入されました。最新の仕様バージョンは、TypeScript の実装とは実行時の挙動が異なりますが、構文は同じです。

                                            このフラグにより、ECMA が定める最新の実行時挙動へ移行できます。

                                            移行の詳細については、3.7 リリースノートを参照してください。

                                            • Default:

                                              true if target is ES2022 or higher, including ESNext; false otherwise.

                                            • Released:

                                              3.7

                                            #Compiler Diagnostics

                                            # Diagnostics - diagnostics

                                            デバッグ用にコンパイラからの診断情報を出力するために使用されていました。このコマンドはよりユーザー向けの結果かつ分かりやすいextendedDiagnosticsのサブセットです。

                                            TypeScript のコンパイラエンジニアからこのフラグを用いて結果を提供するように依頼された場合、代わりに--extendedDiagnosticsを用いても問題ありません。

                                            # Explain Files - 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

                                            このフラグを使うと、TypeScript がコンパイルの際に、どの程度の時間をどこに費やしているかを調査できます。 このフラグは、コードベース全体のパフォーマンス特性を理解するために使われるツールです。

                                            測定の仕方および出力の解釈方法については、wiki のパフォーマンスセクションをご覧ください。

                                            # Generate CPU Profile - generateCpuProfile

                                            このオプションを用いると、TypeScript にコンパイラが実行中の v8 の CPU プロファイルを出力させられます。CPU プロファイルはなぜビルドが遅くなるのかについての示唆を与えてくれます。

                                            このオプションは CLI から--generateCpuProfile tsc-output.cpuprofileを介してのみ使用できます。

                                            sh
                                            npm run tsc --generateCpuProfile tsc-output.cpuprofile

                                            このファイルは Chrome や Edge Developer のような chromium をベースとしたブラウザのCPU profilerで開くことができます。 TypeScript Wiki のパフォーマンスセクションでコンパイラのパフォーマンスについて詳細を学ぶことができます。

                                            • Default:

                                              profile.cpuprofile

                                            • Released:

                                              3.7

                                            # List Emitted Files - listEmittedFiles

                                            コンパイルされ、生成されたファイル名をターミナルに出力します。

                                            このフラグは 2 つのケースで有用です:

                                            • 後続のコマンドでファイル名が処理されるターミナルのビルドチェーンの一部として TypeScript をトランスパイルしたいとき
                                            • TypeScript がコンパイルしてほしいファイルを対象に含めているか分からず、対象ファイル設定を部分的にデバッグしたいとき

                                            例えば、以下のようなときに:

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

                                            以下の設定をすると:

                                            json
                                            {
                                            "compilerOptions": {
                                            "declaration": true,
                                            "listFiles": true
                                            }
                                            }

                                            以下のような path を出力します:

                                            $ npm run tsc path/to/example/index.js path/to/example/index.d.ts

                                            通常、成功すると TypeScript は何も出力しない状態に戻ります。

                                              # List Files - listFiles

                                              コンパイルされるファイル名を出力します。これは、コンパイルしてほしいファイルを TypeScript が対象に含めてくれているかが分からないときに有用です。

                                              例えば、以下のようなときに:

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

                                              以下の設定をすると:

                                              {
                                              "": true
                                              }
                                              }

                                              出力される path は以下のようになります:

                                              $ 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

                                              # Trace Resolution - traceResolution

                                              あるモジュールがコンパイル対象に含まれていない理由をデバッグするために用います。 traceResolutionstrueにすると TypeScript が処理された各々のファイルについてモジュール解決過程の情報を出力するようになります。

                                              この設定についてより詳細に知りたい場合、ハンドブックをご覧ください。

                                              #Projects

                                              # Composite - composite

                                              compositeオプションは、ビルドツール(--buildモードでの TypeScript 自体を含む) がプロジェクトがビルドされているかどうかを迅速に判断できるようにするために特定の制約を適用します。

                                              この設定が有効なとき:

                                              • 明示的に設定されていないrootDirのデフォルト値はtsconfig.jsonファイルを含むディレクトリとなります。

                                              • すべての実装ファイルは、includeパターンにマッチするかfilesリストに含まれなくてはなりません。この制約に違反した場合、tscはどのファイルが指定されていないかを通知します。

                                              • declarationのデフォルト値がtrueになります。

                                              TypeScript のプロジェクト機能についてのドキュメントはハンドブックから参照できます。

                                              # disableReferencedProjectLoad - disableReferencedProjectLoad

                                              複数プロジェクトの TypeScript プログラムでは、TypeScript は利用可能なすべてのプロジェクトをメモリに読み込みます。これにより、「すべての参照元を検索」のような完全なナレッジグラフを必要とするエディタのレスポンスに対して正確な結果を提供することができます。

                                              プロジェクトが大規模な場合は、disableReferencedProjectLoadフラグを使用してすべてのプロジェクトの自動読み込みを無効にすることができます。代わりに、エディタでファイルを開いたときに動的にプロジェクトが読み込まれます。

                                              # Disable Solution Searching - disableSolutionSearching

                                              複合 TypeScript プロジェクトで作業する場合、このオプションはエディタでfind all references定義へ移動などの機能を使う際に含めたくないプロジェクトを宣言する方法を提供します。

                                              このフラグは大規模な複合プロジェクトで応答性を高めるために使用できるものです。

                                              # Disable Source Project Reference Redirect - disableSourceOfProjectReferenceRedirect

                                              複合 TypeScript プロジェクトで作業する場合、このオプションはモジュール間の境界として d.ts ファイルが使用されていた3.7 以前の挙動に戻す方法を提供します。 3.7 にて、信頼できる情報源は TypeScript のファイルになりました。

                                              # Incremental - incremental

                                              最新のコンパイルでのプロジェクトグラフ情報をディスクにファイルとして保存するように TypeScript に指示します。 このオプションはコンパイルの出力先として指定されたフォルダに .tsbuildinfo のファイル群を作成します。 これらのファイルはコンパイルされた JavaScript が実行時に利用することはなく、安全に削除できます。このフラグの詳細については3.4 リリースノートで確認できます。

                                              このファイル群の出力先フォルダを設定する場合、tsBuildInfoFileオプションを利用してください。

                                              # TS Build Info File - tsBuildInfoFile

                                              この設定により、インクリメンタルコンパイル情報を複合プロジェクトの一部として保存するためのファイルを指定できるため、より大きな TypeScript コードベースを迅速に構築できます。 複合プロジェクトについてはハンドブックでより詳しく知ることができます。

                                              このオプションは、TypeScript がプロジェクトのビルド状態を追跡するためのファイルをディスクのどこに保存するかを設定します。 デフォルトは、JavaScript ファイルの出力先と同じフォルダに保存されます。

                                              #Output Formatting

                                              # No Error Truncation - noErrorTruncation

                                              エラーメッセージを切り捨てないようにします。

                                              デフォルト値のfalseの場合、次のようになります。

                                              ts
                                              var x: {
                                              propertyWithAnExceedinglyLongName1: string;
                                              propertyWithAnExceedinglyLongName2: string;
                                              propertyWithAnExceedinglyLongName3: string;
                                              propertyWithAnExceedinglyLongName4: string;
                                              propertyWithAnExceedinglyLongName5: string;
                                              };
                                               
                                              // 型'x'の文字列表現はエラメッセージ中で省略されます
                                              var s: string = x;
                                              Type '{ propertyWithAnExceedinglyLongName1: string; propertyWithAnExceedinglyLongName2: string; propertyWithAnExceedinglyLongName3: string; propertyWithAnExceedinglyLongName4: string; propertyWithAnExceedinglyLongName5: 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; }' is not assignable to type 'string'.
                                              Variable 'x' is used before being assigned.
                                              Try

                                              trueにすると、次のようになります。

                                              ts
                                              var x: {
                                              propertyWithAnExceedinglyLongName1: string;
                                              propertyWithAnExceedinglyLongName2: string;
                                              propertyWithAnExceedinglyLongName3: string;
                                              propertyWithAnExceedinglyLongName4: string;
                                              propertyWithAnExceedinglyLongName5: string;
                                              };
                                               
                                              // 型'x'の文字列表現はエラメッセージ中で省略されます
                                              var s: string = x;
                                              Type '{ propertyWithAnExceedinglyLongName1: string; propertyWithAnExceedinglyLongName2: string; propertyWithAnExceedinglyLongName3: string; propertyWithAnExceedinglyLongName4: string; propertyWithAnExceedinglyLongName5: 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; }' is not assignable to type 'string'.
                                              Variable 'x' is used before being assigned.
                                              Try

                                                # Preserve Watch Output - preserveWatchOutput

                                                watch モードについて、変更が発生するたびにスクリーンをクリアせずに以前の出力をコンソールに出し続けるかどうかを設定します。

                                                • Internal

                                                # Pretty - pretty

                                                エラーやメッセージを文脈や色を使ってスタイリングします。このオプションはデフォルトで有効です— コンパイラから簡潔で単色のメッセージを受け取れるようにすることもできます。

                                                • Default:

                                                  true

                                                #Completeness

                                                # Skip Default Lib Check - skipDefaultLibCheck

                                                代わりに--skipLibCheckを利用してください。デフォルトのライブラリ型定義ファイルをチェックしないようになります。

                                                  # Skip Lib Check - skipLibCheck

                                                  型定義ファイルのチェックをスキップします。

                                                  型システムの精度を犠牲にすることで、コンパイル実行時間を削減します。 例えば、2 つのライブラリが、同じtypeを一貫性の無い方法で定義していたとします。 すべてのd.tsファイルの完全なチェックを行わずに、TypeScript はアプリケーション内のソースコードで明示的に参照しているコードの型をチェックします。

                                                  skipLibCheckの利用を検討する一般的なケースは、あるライブラリの型定義がnode_modules内にコピーされて複数存在している場合です。 このようなケースでは、 yarn’s resolutionsのような機能の利用を検討してツリーにおける該当の依存関係のコピーが 1 つだけであることを確認するか、 追加のツールを使わずに問題を修正するために依存関係の解決を理解して、コピーが 1 つだけであることを確認する方法を調査する必要があります。

                                                  • Recommended
                                                  • Released:

                                                    2.0

                                                  #コマンドライン

                                                  #Watch Options

                                                  TypeScript 3.8 にてディレクトリを監視するための新戦略をリリースしました。これは、node_modules の変更を効率的に検知するために極めて重要なものです。

                                                  Linux のような OS において、TypeScript は 依存関係の変更を検出するために、node_modules と多くのサブディレクトリに、(ファイルウォッチャーではなく)ディレクトリウォッチャーをインストールします。 なぜなら、利用できるファイルウォッチャーの数を、node_modules のファイル数がしばしば上回る一方で、追跡するディレクトリ数は少なく済むからです。

                                                  各プロジェクトは異なる戦略の下でより良く動作する可能性もあり、逆にこの新しいアプローチが一連の作業の流れでうまく動作しない可能性もあります。そのため、TypeScript 3.8 では新しく watchOptions フィールドが導入されました。このフィールドでは、ファイルやディレクトリを追跡する為に、どの監視戦略を使用すべきか、compiler/language service に伝えることができます。

                                                  # Assume Changes Only Affect Direct Dependencies - assumeChangesOnlyAffectDirectDependencies

                                                  このオプションを設定すると、TypeScript は本当に影響を受ける可能性があるすべてのファイルの再チェック/再ビルドを避け、変更されたファイルとそれらを直接 import しているファイルのみを再チェック/再ビルドするようになります。

                                                  これは監視アルゴリズムの「高速で緩い」実装と見なせます。これにより、すべてのコンパイルエラーメッセージを得るためにフルビルドが必要になりますが、インクリメンタルビルドの再ビルド時間を大幅に短縮できます。

                                                  # watchFile - watchFile

                                                  個々のファイルを監視する方法を指定します。

                                                  • fixedPollingInterval: すべてのファイルの変更を一定間隔で毎秒数回チェックします。
                                                  • priorityPollingInterval: すべてのファイルの変更を毎秒数回チェックしますが、ヒューリスティックスを使用して他のファイルよりも少ない頻度で特定のタイプのファイルをチェックします。
                                                  • dynamicPriorityPolling: 変更頻度の低いファイルがチェックされる頻度が低くなるような動的なキューを使用します。
                                                  • useFsEvents (デフォルト): オペレーティングシステム/ファイルシステムのネイティブイベントの使用をファイルの変更に試みます。
                                                  • useFsEventsOnParentDirectory: ファイルの親ディレクトリの変更を監視するためにオペレーティングシステム/ファイルシステムのネイティブイベントを使用を試みます。
                                                  • Allowed:
                                                    • fixedpollinginterval

                                                    • prioritypollinginterval

                                                    • dynamicprioritypolling

                                                    • fixedchunksizepolling

                                                    • usefsevents

                                                    • usefseventsonparentdirectory

                                                  • Released:

                                                    3.8

                                                  # watchDirectory - watchDirectory

                                                  再帰的なファイル監視機能を持たないシステムで、ディレクトリツリー全体を監視する方法を指定します。

                                                  • fixedPollingInterval: すべてのディレクトリの変更を一定間隔で毎秒数回チェックします。
                                                  • dynamicPriorityPolling: 変更頻度の低いディレクトリがチェックされる頻度が低くなるような動的なキューを使用します。
                                                  • useFsEvents (デフォルト): ディレクトリの変更に対するオペレーティングシステム/ファイルシステムのネイティブイベントの使用を試みます。
                                                  • Allowed:
                                                    • usefsevents

                                                    • fixedpollinginterval

                                                    • dynamicprioritypolling

                                                    • fixedchunksizepolling

                                                  • Released:

                                                    3.8

                                                  # fallbackPolling - fallbackPolling

                                                  ファイルシステムのイベントを使用するときに、システムがネイティブのファイルウォッチャーを使い切ったり、ネイティブのファイルウォッチャーが対応していない場合、どのようなポーリング戦略を行使するかを指定するオプションです。

                                                  • fixedPollingInterval: 一定の間隔を開けて、1 秒間に数回、全ファイルをチェックします。
                                                  • priorityPollingInterval: 1 秒間に数回、全ファイルをチェックします。しかし、特定の種類のファイルには発見的手法を使用して、他ファイルよりも低頻度でチェックします。
                                                  • dynamicPriorityPolling: 変更頻度の少ないファイルは、他よりも低頻度でチェックされるように動的キューを使用します。
                                                  • synchronousWatchDirectory: ディレクトリの遅延監視を無効にします。遅延監視機能は、沢山のファイル変更が一度に引き起こされる場合は役立ちますが(例: npm install による node_modules の変更)、あまり一般的な構成ではないときに、この遅延監視フラグを無効にしたくなるかもしれません。
                                                  • Allowed:
                                                    • fixedinterval

                                                    • priorityinterval

                                                    • dynamicpriority

                                                    • fixedchunksize

                                                  • Released:

                                                    3.8

                                                  # Synchronous Watch Directory - 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": {
                                                  }
                                                  }

                                                    # Exclude Directories - 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/*"]
                                                    }
                                                    }

                                                      # Exclude Files - 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

                                                        Disables automatic type acquisition in JavaScript projects:

                                                        json
                                                        {
                                                        "typeAcquisition": {
                                                        "enable": false
                                                        }
                                                        }

                                                          # 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"]
                                                          }
                                                          }

                                                          # Disable Filename Based Type Acquisition - 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
                                                          }
                                                          }