Compiler Options

" compilerOptions "

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

Specifies an allowlist of files to include in the program. An error occurs if any of the files can’t be found.

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

This is useful when you only have a small number of files and don’t need to use a glob to reference many files. If you need that then use include .

  • Default:

    false

  • Related:
    • include

    • exclude

      # Extends - extends

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

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

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

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

      Example

      configs/base.json :

      tsconfig.json :

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

      tsconfig.nostrictnull.json :

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

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

      • Default:

        false

      • Released:

        2.1

        # Include - include

        Specifies an array of filenames or patterns to include in the program. These filenames are resolved relative to the directory containing the tsconfig.json file.

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

        Which would include:

        .
        ├── scripts ⨯
        │ ├── lint.ts ⨯
        │ ├── update_deps.ts ⨯
        │ └── utils.ts ⨯
        ├── src ✓
        │ ├── client ✓
        │ │ ├── index.ts ✓
        │ │ └── utils.ts ✓
        │ ├── server ✓
        │ │ └── index.ts ✓
        ├── tests ✓
        │ ├── app.test.ts ✓
        │ ├── utils.ts ✓
        │ └── tests.d.ts ✓
        ├── package.json
        ├── tsconfig.json
        └── yarn.lock

        include and exclude support wildcard characters to make glob patterns:

      • * matches zero or more characters (excluding directory separators)
      • ? matches any one character (excluding directory separators)
      • **/ matches any directory nested to any level
      • If the last path segment in a pattern does not contain a file extension or wildcard character, then it is treated as a directory, and files with supported extensions inside that directory are included (e.g. .ts , .tsx , and .d.ts by default, with .js and .jsx if allowJs is set to true).

        • Default:

          [] if files is specified; **/* otherwise.

        • Related:
          • files

          • exclude

          • Released:

            2.0

            # Exclude - exclude

            Specifies an array of filenames or patterns that should be skipped when resolving include .

            Important : exclude only changes which files are included as a result of the include setting. A file specified by exclude can still become part of your codebase due to an import statement in your code, a types inclusion, a /// <reference directive, or being specified in the files list.

            It is not a mechanism that prevents a file from being included in the codebase - it simply changes what the include setting finds.

            • Default:

              node_modules bower_components jspm_packages outDir

            • Related:
              • include

              • files

                # References - references

                Project references are a way to structure your TypeScript programs into smaller pieces. Using Project References can greatly improve build and editor interaction times, enforce logical separation between components, and organize your code in new and improved ways.

                You can read more about how references works in the Project References section of the handbook

                • Default:

                  false

                • undefined (default) provide suggestions as warnings to editors
                • true unreachable code is ignored
                • false raises compiler errors about unreachable code
                • These warnings are only about code which is provably unreachable due to the use of JavaScript syntax, for example:

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

                With "allowUnreachableCode": false :

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

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

                • Released:

                  1.8

                  # Allow Unused Labels - allowUnusedLabels

                  When:

                • undefined (default) provide suggestions as warnings to editors
                • true unused labels are ignored
                • false raises compiler errors about unused labels
                • Labels are very rare in JavaScript and typically indicate an attempt to write an object literal:

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

                  1.8

                  # Always Strict - alwaysStrict

                  Ensures that your files are parsed in the ECMAScript strict mode, and emit “use strict” for each source file.

                  ECMAScript strict mode was introduced in ES5 and provides behavior tweaks to the runtime of the JavaScript engine to improve performance, and makes a set of errors throw instead of silently ignoring them.

                  • Recommended
                  • Default:

                    true if strict ; false otherwise.

                  • Related:
                    • strict

                    • 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

                        Report errors for fallthrough cases in switch statements. Ensures that any non-empty case inside a switch statement includes either break , return , or throw . This means you won’t accidentally ship a case fallthrough bug.

                        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
                        • Released:

                          1.8

                          # No Implicit Any - noImplicitAny

                          In some cases where no type annotations are present, TypeScript will fall back to a type of any for a variable when it cannot infer the type.

                          This can cause some errors to be missed, for example:

                          ts
                          function fn(s) {
                          // No error?
                          console.log(s.subtr(3));
                          }
                          fn(42);
                          Try

                          Turning on noImplicitAny however TypeScript will issue an error whenever it would have inferred 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:
                            • strict

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

                                4.3

                                # No Implicit Returns - noImplicitReturns

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

                                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
                                • Released:

                                  1.8

                                  # No Implicit This - noImplicitThis

                                  Raise error on ‘this’ expressions with an implied ‘any’ type.

                                  For example, the class below returns a function which tries to access this.width and this.height – but the context for this inside the function inside getAreaFunction is not the instance of the Rectangle.

                                  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:
                                    • strict

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

                                      • Released:

                                        4.2

                                        # No Unchecked Indexed Access - noUncheckedIndexedAccess

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

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

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

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

                                          4.1

                                          # No Unused Locals - noUnusedLocals

                                          Report errors on unused local variables.

                                          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
                                          • Released:

                                            2.0

                                            # No Unused Parameters - noUnusedParameters

                                            Report errors on unused parameters in functions.

                                            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
                                            • Released:

                                              2.0

                                              # Strict - strict

                                              The strict flag enables a wide range of type checking behavior that results in stronger guarantees of program correctness. Turning this on is equivalent to enabling all of the strict mode family options, which are outlined below. You can then turn off individual strict mode family checks as needed.

                                              Future versions of TypeScript may introduce additional stricter checking under this flag, so upgrades of TypeScript might result in new type errors in your program. When appropriate and possible, a corresponding flag will be added to disable that behavior.

                                              • Recommended
                                              • Related:
                                                • alwaysStrict

                                                • strictNullChecks

                                                • strictBindCallApply

                                                • strictFunctionTypes

                                                • strictPropertyInitialization

                                                • noImplicitAny

                                                • noImplicitThis

                                                • useUnknownInCatchVariables

                                                • Released:

                                                  2.3

                                                  # Strict Bind Call Apply - strictBindCallApply

                                                  When set, TypeScript will check that the built-in methods of functions call , bind , and apply are invoked with correct argument for the underlying function:

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

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

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

                                                    true if strict ; false otherwise.

                                                  • Related:
                                                    • strict

                                                    • Released:

                                                      3.2

                                                      # Strict Function Types - strictFunctionTypes

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

                                                      Here’s a basic example with strictFunctionTypes off:

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

                                                      With strictFunctionTypes on , the error is correctly detected:

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

                                                      During development of this feature, we discovered a large number of inherently unsafe class hierarchies, including some in the DOM. Because of this, the setting only applies to functions written in function syntax, not to those in method syntax:

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

                                                        true if strict ; false otherwise.

                                                      • Related:
                                                        • strict

                                                        • Released:

                                                          2.6

                                                          # Strict Null Checks - strictNullChecks

                                                          When strictNullChecks is false , null and undefined are effectively ignored by the language. This can lead to unexpected errors at runtime.

                                                          When strictNullChecks is true , null and undefined have their own distinct types and you’ll get a type error if you try to use them where a concrete value is expected.

                                                          For example with this TypeScript code, users.find has no guarantee that it will actually find a user, but you can write code as though it will:

                                                          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

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

                                                          ts
                                                          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

                                                          The second example failed because the array’s find function looks a bit like this simplification:

                                                          ts
                                                          // When strictNullChecks: true
                                                          type Array = {
                                                          find(predicate: (value: any, index: number) => boolean): S | undefined;
                                                          };
                                                          // When strictNullChecks: false the undefined is removed from the type system,
                                                          // allowing you to write code which assumes it always found a result
                                                          type Array = {
                                                          find(predicate: (value: any, index: number) => boolean): S;
                                                          };
                                                          • Recommended
                                                          • Default:

                                                            true if strict ; false otherwise.

                                                          • Related:
                                                            • strict

                                                            • Released:

                                                              2.0

                                                              # Strict Property Initialization - strictPropertyInitialization

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

                                                              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;
                                                              // Note that this.email is not set
                                                              }
                                                              }
                                                              Try

                                                              In the above case:

                                                            • this.name is set specifically.
                                                            • this.accountType is set by default.
                                                            • this.email is not set and raises an error.
                                                            • this.address is declared as potentially undefined which means it does not have to be set.
                                                              • Recommended
                                                              • Default:

                                                                true if strict ; false otherwise.

                                                              • Related:
                                                                • strict

                                                                • 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: unknown) {
                                                                  // 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:
                                                                    • strict

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

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

                                                                      allowUmdGlobalAccess 设置为 true 时,将允许你在模块文件中以全局变量的形式访问 UMD 的导出。 模块文件是具有或同时导入、导出的文件。当未设置这个选项时,使用 UMD 模块的导出需要首先导入声明。

                                                                      一个典型场景是:在一个 Web 项目中, 您知道特定的库(如 jQuery 或 Lodash )在运行时总是可用的,但您无法通过导入来使用他们。

                                                                      • Released:

                                                                        3.5

                                                                        # 基准目录 - baseUrl

                                                                        可以让您设置解析非绝对路径模块名时的基准目录。

                                                                        你可以定义一个根目录,以进行绝对路径文件解析。例如:

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

                                                                        在这个项目中被配置为 "baseUrl": "./" ,TypeScript 将会从首先寻找与 tsconfig.json 处于相同目录的文件。

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

                                                                        当你厌倦了导入文件时总是 "../" "./" ,或需要在移动文件时更改路径,这是一个很好的解决方法。

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

                                                                        • Related:
                                                                          • moduleResolution

                                                                          • resolvePackageJsonExports

                                                                          • resolvePackageJsonImports

                                                                            # 模块 - module

                                                                            设置程序的模块系统。在 模块 参考页面获取更多信息。你很可能要用 "CommonJS"

                                                                            改变 module 可能会影响 moduleResolution ,它也有 一个参考页

                                                                            下面是这个文件的一些输出例子:

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

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

                                                                            ES2020

                                                                            ts
                                                                            import { valueOfPi } from "./constants";
                                                                            export const twoPi = valueOfPi * 2;
                                                                             
                                                                            Try
                                                                            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
                                                                            • Default:

                                                                              CommonJS if target is ES3 or ES5 ; ES6 / ES2015 otherwise.

                                                                            • Allowed:
                                                                              • none

                                                                              • commonjs

                                                                              • system

                                                                              • es6 / es2015

                                                                              • es2020

                                                                              • es2022

                                                                              • esnext

                                                                              • node16

                                                                              • nodenext

                                                                              • preserve

                                                                              • Related:
                                                                                • moduleResolution

                                                                                • esModuleInterop

                                                                                • allowImportingTsExtensions

                                                                                • allowArbitraryExtensions

                                                                                • resolveJsonModule

                                                                                • Released:

                                                                                  1.0

                                                                                  # 模块解析 - moduleResolution

                                                                                  指定模块解析策略: 'node' (Node.js) 或 'classic' (在 TypeScript 1.6 版本之前使用)。 你可能不需要在新代码中使用 classic

                                                                                  这里有一个关于 模块解析 的手册参考。

                                                                                  • Default:

                                                                                    Classic if module is AMD , UMD , System , or ES6 / ES2015 ; Matches if module is node16 or nodenext ; Node otherwise.

                                                                                  • Allowed:
                                                                                    • classic

                                                                                    • node10 / node

                                                                                    • node16

                                                                                    • nodenext

                                                                                    • bundler

                                                                                    • Related:
                                                                                      • module

                                                                                      • paths

                                                                                      • baseUrl

                                                                                      • rootDirs

                                                                                      • moduleSuffixes

                                                                                      • customConditions

                                                                                      • resolvePackageJsonExports

                                                                                      • resolvePackageJsonImports

                                                                                        # Module Suffixes - moduleSuffixes

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

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

                                                                                        • Released:

                                                                                          4.7

                                                                                          # No Resolve - noResolve

                                                                                          By default, TypeScript will examine the initial set of files for import and <reference directives and add these resolved files to your program.

                                                                                          If noResolve is set, this process doesn’t happen. However, import statements are still checked to see if they resolve to a valid module, so you’ll need to make sure this is satisfied by some other means.

                                                                                          一些将模块导入重新映射到相对于 baseUrl 路径的配置。 手册 中有更多关于 paths 的内容。

                                                                                          paths 可以允许你声明 TypeScript 应该如何解析你的 require / import

                                                                                          {
                                                                                          "": ".", // this must be specified if "paths" is specified.
                                                                                          "": {
                                                                                          "jquery": ["node_modules/jquery/dist/jquery"] // this mapping is relative to "baseUrl"
                                                                                          }
                                                                                          }
                                                                                          }

                                                                                          这将使你可以写 import "jquery" ,并且在本地获得所有正确的类型。

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

                                                                                          这种情况下,你可以告诉 TypeScript 文件解析器支持一些自定义的前缀来寻找代码。 这种模式可以避免在你的代码中出现过长的相对路径。

                                                                                          Allows importing modules with a .json extension, which is a common practice in node projects. This includes generating a type for the import based on the static JSON shape.

                                                                                          TypeScript does not support resolving JSON files by default:

                                                                                          ts
                                                                                          // @filename: settings.json
                                                                                          {
                                                                                          "repo": "TypeScript",
                                                                                          "dry": false,
                                                                                          "debug": false
                                                                                          }
                                                                                          // @filename: index.ts
                                                                                          import settings from "./settings.json";
                                                                                          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.
                                                                                           
                                                                                          settings.debug === true;
                                                                                          settings.dry === 2;
                                                                                          Try

                                                                                          Enabling the option allows importing JSON, and validating the types in that JSON file.

                                                                                          ts
                                                                                          // @filename: settings.json
                                                                                          {
                                                                                          "repo": "TypeScript",
                                                                                          "dry": false,
                                                                                          "debug": false
                                                                                          }
                                                                                          // @filename: index.ts
                                                                                          import settings from "./settings.json";
                                                                                           
                                                                                          settings.debug === true;
                                                                                          settings.dry === 2;
                                                                                          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.
                                                                                          Try

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

                                                                                          • Default:

                                                                                            true when moduleResolution is node16 , nodenext , or bundler ; otherwise false

                                                                                          • Related:
                                                                                            • moduleResolution

                                                                                            • customConditions

                                                                                            • resolvePackageJsonImports

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

                                                                                              • Default:

                                                                                                true when moduleResolution is node16 , nodenext , or bundler ; otherwise false

                                                                                              • Related:
                                                                                                • moduleResolution

                                                                                                • customConditions

                                                                                                • resolvePackageJsonExports

                                                                                                  # 根目录 - rootDir

                                                                                                  默认 : 所有输入的非声明文件中的最长公共路径。若 composite 被指定,则是包含 tsconfig.json 文件的目录。

                                                                                                  当 TypeScript 编译文件时,它在输出目录中保持与输入目录中相同的目录结构。

                                                                                                  例如,假设你有一些输入文件:

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

                                                                                                  rootDir 推断的结构是所有非声明输入文件的最长公共路径,在例子中为 core/

                                                                                                  如果你的 outDir dist ,TypeScript 将会生成这样的文件树:

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

                                                                                                  但你可能希望让 core 成为输出目录结构的一部分。 通过在 tsconfig.json 中指定 rootDir: "." ,TypeScript 将会生成这样的文件树:

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

                                                                                                  重要的是, rootDir 不会影响哪些文件被包含在编译中 。 它与 tsconfig.json include exclude ,or files 的选项没有关系。

                                                                                                  请注意,TypeScript 永远不会将输出文件写入 outDir 之外的目录,也不会忽略生成某些文件。 处于这个原因, rootDir 页强制要求所有需要被生成的文件都在 rootDir 路径下。

                                                                                                  例如,假设你有这样的文件树:

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

                                                                                                  rootDir 指定为 core 并且 include 指定为 * 是错误的,因为它会创建一个文件( helpers.ts ),这个文件会被生成在 outDir 之外 (即 ../helpers.js )。

                                                                                                  • Default:

                                                                                                    Computed from the list of input files.

                                                                                                  • Released:

                                                                                                    1.5

                                                                                                    # 根目录 - rootDirs

                                                                                                    通过 rootDirs ,你可以告诉编译器有许多“虚拟”的目录作为一个根目录。这将会允许编译器在这些“虚拟”目录中解析相对应的模块导入,就像它们被合并到同一目录中一样。

                                                                                                    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

                                                                                                      # 类型根路径 - typeRoots

                                                                                                      默认情况下,所有 可见 的 ” @types ” 包都将包含在你的编译过程中。 在 node_modules/@types 中的任何包都被认为是 可见 的。 例如,这意味着包含 ./node_modules/@types/ ../node_modules/@types/ ../../node_modules/@types/ 中所有的包。

                                                                                                      typeRoots 被指定, 仅有 typeRoots 下的包会被包含。例如:

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

                                                                                                      这个配置文件将包含 ./typings ./vendor/types 下的所有包,而不包括 ./node_modules/@types 下的。其中所有的路径都是相对于 tsconfig.json

                                                                                                      • Related:
                                                                                                        • types

                                                                                                          # 类型 - types

                                                                                                          默认情况下,所有 可见 的 ” @types ” 包都将包含在你的编译过程中。 在 node_modules/@types 中的任何包都被认为是 可见 的。 例如,这意味着包含 ./node_modules/@types/ ../node_modules/@types/ ../../node_modules/@types/ 中所有的包。。

                                                                                                          types 被指定,则只有列出的包才会被包含在全局范围内。例如:

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

                                                                                                          这个 tsconfig.json 文件将 只会 包含 ./node_modules/@types/node ./node_modules/@types/jest ./node_modules/@types/express 。 其他在 node_modules/@types/* 下的包将不会被包含。

                                                                                                          这会影响什么?

                                                                                                          此选项不会影响 @types/* 如何被包含在你的代码中,例如你在有上面例子里 compilerOptions 的环境中写了这样的代码:

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

                                                                                                          moment 导入会有完整的类型。

                                                                                                          当你设置了这个选项,通过不在 types 数组中包含,它将:

                                                                                                        • 不会再你的项目中添加全局声明(例如 node 中的 process 或 Jest 中的 expect
                                                                                                        • 导出不会出现再自动导入的建议中
                                                                                                        • 此功能与 类型根路径 不同的是,它只指定你想要包含的具体类型,而 类型根路径 支持你想要特定的文件夹。

                                                                                                          • Related:
                                                                                                            • typeRoots

                                                                                                              # Emit

                                                                                                              # 声明 - declaration

                                                                                                              为你工程中的每个 TypeScript 或 JavaScript 文件生成 .d.ts 文件。 这些 .d.ts 文件是描述模块外部 API 的类型定义文件。 像 TypeScript 这样的哦你根据可以通过 .d.ts 文件为非类型化的代码提供 intellisense 和精确的类型。

                                                                                                              declaration 设置为 true 时,用编译器执行下面的 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

                                                                                                              当使用 .d.ts 文件处理 JavaScript 文件时,你可能需要使用 emitDeclarationOnly outDir 来确保 JavaScript 文件不会被覆盖。

                                                                                                              • Default:

                                                                                                                true if composite ; false otherwise.

                                                                                                              • Related:
                                                                                                                • declarationDir

                                                                                                                • emitDeclarationOnly

                                                                                                                • Released:

                                                                                                                  1.0

                                                                                                                  # Declaration Dir - declarationDir

                                                                                                                  Offers a way to configure the root directory for where declaration files are emitted.

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

                                                                                                                  with this tsconfig.json :

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

                                                                                                                  Would place the d.ts for the index.ts in a types folder:

                                                                                                                  example
                                                                                                                  ├── index.js
                                                                                                                  ├── index.ts
                                                                                                                  ├── package.json
                                                                                                                  ├── tsconfig.json
                                                                                                                  └── types
                                                                                                                  └── index.d.ts
                                                                                                                  • Related:
                                                                                                                    • declaration

                                                                                                                    • Released:

                                                                                                                      2.0

                                                                                                                      # Declaration Map - declarationMap

                                                                                                                      Generates a source map for .d.ts files which map back to the original .ts source file. This will allow editors such as VS Code to go to the original .ts file when using features like Go to Definition .

                                                                                                                      You should strongly consider turning this on if you’re using project references.

                                                                                                                      • Released:

                                                                                                                        2.9

                                                                                                                        # 迭代器降级 - downlevelIteration

                                                                                                                        ‘降级’ 是 TypeScript 的术语,指用于转换到旧版本的 JavaScript。 这个选项是为了在旧版 Javascript 运行时上更准确的实现现代 JavaScript 迭代器的概念。

                                                                                                                        ECMAScript 6 增加了几个新的迭代器原语: for / of 循环( for (el of arr) ),数组展开( [a, ...b] ),参数展开( fn(...args) )和 Symbol.iterator

                                                                                                                        如果 Symbol.iterator 存在的话, --downlevelIteration 将允许在 ES5 环境更准确的使用这些迭代原语。

                                                                                                                        例: for / of 的效果

                                                                                                                        对于 TypeScript 代码:

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

                                                                                                                        如果没有启用 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

                                                                                                                        这通常是人们所期望的,但是它并不是 100% 符合 ECMAScript 迭代器协议。 某些字符串,例如 emoji (😜),其 .length 为 2(甚至更多),但在 for-of 循环中应只有一次迭代。 可以在 Jonathan New 的这篇文章中 找到更详细的解释。

                                                                                                                        downlevelIteration 启用时,TypeScript 将会使用辅助函数来检查 Symbol.iterator 的实现(无论是原生实现还是 polyfill)。 如果没有实现,则将会回退到基于索引的迭代。

                                                                                                                        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

                                                                                                                        你也可以通过 importHelpers 来使用 tslib 以减少被内联的 JavaScript 的数量:

                                                                                                                        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

                                                                                                                        注: 如果在运行时不存在 Symbol.iterator ,启用 downlevelIteration 将不会提高合规性。

                                                                                                                        例:数组展开的效果

                                                                                                                        这是一个数组展开:

                                                                                                                        js
                                                                                                                        // 构建一个新的数组,其元素首先为 1,然后是 arr2 的元素。
                                                                                                                        const arr = [1, ...arr2];

                                                                                                                        根据描述,听起来很容易降级到 ES5:

                                                                                                                        js
                                                                                                                        // The same, right?
                                                                                                                        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 的行为。

                                                                                                                        • Related:
                                                                                                                          • importHelpers

                                                                                                                          • Released:

                                                                                                                            2.3

                                                                                                                            # Emit BOM - emitBOM

                                                                                                                            Controls whether TypeScript will emit a byte order mark (BOM) when writing output files. Some runtime environments require a BOM to correctly interpret a JavaScript files; others require that it is not present. The default value of false is generally best unless you have a reason to change it.

                                                                                                                            This setting is useful in two cases:

                                                                                                                          • You are using a transpiler other than TypeScript to generate your JavaScript.
                                                                                                                          • You are using TypeScript to only generate d.ts files for your consumers.
                                                                                                                            • Related:
                                                                                                                              • declaration

                                                                                                                              • Released:

                                                                                                                                2.8

                                                                                                                                # 导入辅助 - importHelpers

                                                                                                                                对于某些降级行为,TypeScript 使用一些辅助代码来进行操作。例如继承类,展开数组或对象,以及异步操作。 默认情况下,这些辅助代码被插入到使用它们的文件中。 如果在许多不同的模块中使用相同的辅助代码,则可能会导致代码重复。

                                                                                                                                如果启用了 importHelpers 选项,这些辅助函数将从 tslib 中被导入。 你需要确保 tslib 模块在运行时可以被导入。 这只影响模块,全局脚本文件不会尝试导入模块。

                                                                                                                                例如,对于如下 TypeScript 代码:

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

                                                                                                                                开启 downlevelIteration 并且 importHelpers 仍为 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

                                                                                                                                同时开始 downlevelIteration importHelpers

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

                                                                                                                                当你提供了自行实现的这些函数时,你可以使用 noEmitHelpers

                                                                                                                                • Related:
                                                                                                                                  • noEmitHelpers

                                                                                                                                  • downlevelIteration

                                                                                                                                    # Imports Not Used As Values - importsNotUsedAsValues

                                                                                                                                    Deprecated in favor of verbatimModuleSyntax .

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

                                                                                                                                    remove : The default behavior of dropping import statements which only reference types.

                                                                                                                                    preserve : Preserves all import statements whose values or types are never used. This can cause imports/side-effects to be preserved.

                                                                                                                                    error : This preserves all imports (the same as the preserve option), but will error when a value import is only used as a type. This might be useful if you want to ensure no values are being accidentally imported, but still make side-effect imports explicit.

                                                                                                                                    This flag works because you can use import type to explicitly create an import statement which should never be emitted into JavaScript.

                                                                                                                                    • Default:

                                                                                                                                      remove

                                                                                                                                    • Allowed:
                                                                                                                                      • remove

                                                                                                                                      • preserve

                                                                                                                                      • error

                                                                                                                                      • Related:
                                                                                                                                        • preserveValueImports

                                                                                                                                        • verbatimModuleSyntax

                                                                                                                                        • Released:

                                                                                                                                          3.8

                                                                                                                                          # Inline Source Map - inlineSourceMap

                                                                                                                                          When set, instead of writing out a .js.map file to provide source maps, TypeScript will embed the source map content in the .js files. Although this results in larger JS files, it can be convenient in some scenarios. For example, you might want to debug JS files on a webserver that doesn’t allow .map files to be served.

                                                                                                                                          Mutually exclusive with sourceMap .

                                                                                                                                          For example, with this TypeScript:

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

                                                                                                                                          Converts to this JavaScript:

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

                                                                                                                                          Then enable building it with inlineSourceMap enabled there is a comment at the bottom of the file which includes a source-map for the file.

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

                                                                                                                                            1.5

                                                                                                                                            # Inline Sources - inlineSources

                                                                                                                                            When set, TypeScript will include the original content of the .ts file as an embedded string in the source map (using the source map’s sourcesContent property). This is often useful in the same cases as inlineSourceMap .

                                                                                                                                            Requires either sourceMap or inlineSourceMap to be set.

                                                                                                                                            For example, with this TypeScript:

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

                                                                                                                                            By default converts to this JavaScript:

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

                                                                                                                                            Then enable building it with inlineSources and inlineSourceMap enabled there is a comment at the bottom of the file which includes a source-map for the file. Note that the end is different from the example in inlineSourceMap because the source-map now contains the original source code also.

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

                                                                                                                                              1.5

                                                                                                                                              # Map Root - mapRoot

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

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

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

                                                                                                                                              Specify the end of line sequence to be used when emitting files: ‘CRLF’ (dos) or ‘LF’ (unix).

                                                                                                                                              • Default:

                                                                                                                                                lf

                                                                                                                                              • Allowed:
                                                                                                                                                • crlf

                                                                                                                                                • Released:

                                                                                                                                                  1.5

                                                                                                                                                  # 禁止生成 - noEmit

                                                                                                                                                  禁止编译器生成文件,例如 JavaScript 代码,source-map 或声明。

                                                                                                                                                  这为另一个工具提供了空间,例如用 Babel swc 来处理将 TypeScript 转换为可以在 JavaScript 环境中运行的文件的过程。

                                                                                                                                                  然后你可以使用 TypeScript 作为提供编辑器集成的工具,或用来对源码进行类型检查。

                                                                                                                                                  Instead of importing helpers with importHelpers , you can provide implementations in the global scope for the helpers you use and completely turn off emitting of helper functions.

                                                                                                                                                  For example, using this async function in ES5 requires a await -like function and generator -like function to run:

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

                                                                                                                                                  Which creates quite a lot of 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

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

                                                                                                                                                  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
                                                                                                                                                  • Related:
                                                                                                                                                    • importHelpers

                                                                                                                                                    • Released:

                                                                                                                                                      1.5

                                                                                                                                                      # No Emit On Error - noEmitOnError

                                                                                                                                                      Do not emit compiler output files like JavaScript source code, source-maps or declarations if any errors were reported.

                                                                                                                                                      This defaults to false , making it easier to work with TypeScript in a watch-like environment where you may want to see results of changes to your code in another environment before making sure all errors are resolved.

                                                                                                                                                      • Released:

                                                                                                                                                        1.4

                                                                                                                                                        # 输出目录 - outDir

                                                                                                                                                        如果被指定, .js (以及 .d.ts , .js.map 等)将会被生成到这个目录下。 原始源文件的目录将会被保留,如果计算出的根目录不是你想要的,可以查看 rootDir

                                                                                                                                                        如果没有指定, .js 将被生成至于生成它们的 .ts 文件相同的目录中:

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

                                                                                                                                                        使用类似这样的 tsconfig.json

                                                                                                                                                        {
                                                                                                                                                        "": "dist"
                                                                                                                                                        }
                                                                                                                                                        }

                                                                                                                                                        使用这些配置运行 tsc 时,会将文件移动到指定的 dist 文件夹中:

                                                                                                                                                        sh
                                                                                                                                                        $ tsc
                                                                                                                                                        example
                                                                                                                                                        ├── dist
                                                                                                                                                        │ └── index.js
                                                                                                                                                        ├── index.ts
                                                                                                                                                        └── tsconfig.json
                                                                                                                                                        • Related:
                                                                                                                                                          • out

                                                                                                                                                          • outFile

                                                                                                                                                            # 输出文件 - outFile

                                                                                                                                                            如果被指定,所有 全局 (非模块) 文件将被合并到指定的单个输出文件中。

                                                                                                                                                            如果 module system amd ,所有模块文件也将在所有全局内容之后被合并到这个文件中。

                                                                                                                                                            注:除非 module None System AMD , 否则不能使用 outFile 。 这个选项 不能 用来打包 CommonJS 或 ES6 模块。

                                                                                                                                                            • Related:
                                                                                                                                                              • out

                                                                                                                                                              • outDir

                                                                                                                                                              • Released:

                                                                                                                                                                1.0

                                                                                                                                                                # Preserve Const Enums - preserveConstEnums

                                                                                                                                                                Do not erase const enum declarations in generated code. const enum s provide a way to reduce the overall memory footprint of your application at runtime by emitting the enum value instead of a reference.

                                                                                                                                                                For example with this TypeScript:

                                                                                                                                                                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

                                                                                                                                                                The default const enum behavior is to convert any Album.Something to the corresponding number literal, and to remove a reference to the enum from the JavaScript completely.

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

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

                                                                                                                                                                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

                                                                                                                                                                This essentially makes such const enums a source-code feature only, with no runtime traces.

                                                                                                                                                                • Default:

                                                                                                                                                                  true if isolatedModules ; false otherwise.

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

                                                                                                                                                                  • Related:
                                                                                                                                                                    • isolatedModules

                                                                                                                                                                    • importsNotUsedAsValues

                                                                                                                                                                    • verbatimModuleSyntax

                                                                                                                                                                    • Released:

                                                                                                                                                                      4.5

                                                                                                                                                                      # 移除注释 - removeComments

                                                                                                                                                                      当转换为 JavaScript 时,忽略所有 TypeScript 文件中的注释。默认为 false

                                                                                                                                                                      例如,这是一个有 JSDoc 注释的 TypeScript 文件:

                                                                                                                                                                      ts
                                                                                                                                                                      /** 'Hello world' 的葡萄牙语翻译 */
                                                                                                                                                                      export const helloWorldPTBR = "Olá Mundo";

                                                                                                                                                                      当然 removeComments 被设置为 true

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

                                                                                                                                                                      未设置 removeComments 或被设置为 false

                                                                                                                                                                      ts
                                                                                                                                                                      /** 'Hello world' 的葡萄牙语翻译 */
                                                                                                                                                                      export const helloWorldPTBR = "Olá Mundo";
                                                                                                                                                                       
                                                                                                                                                                      Try

                                                                                                                                                                      这意味着你的注释将呈现在 JavaScript 中。

                                                                                                                                                                      启用生成 sourcemap files 。 这些文件允许调试器和其他工具在使用实际生成的 JavaScript 文件时,显示原始的 TypeScript 代码。 Source map 文件以 .js.map (或 .jsx.map )文件的形式被生成到相应的 .js 文件输出旁。

                                                                                                                                                                      .js 文件将会包含一个 sourcemap 注释,以向外部工具表明文件在哪里。例如:

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

                                                                                                                                                                      在将 sourceMap 设置为 true 的情况下编译,会生成如下 JavaScript 文件:

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

                                                                                                                                                                      并且会生成这个 json 格式的 sourcemap

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

                                                                                                                                                                      Specify the location where a debugger should locate TypeScript files instead of relative source locations. This string is treated verbatim inside the source-map where you can use a path or a URL:

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

                                                                                                                                                                      Would declare that index.js will have a source file at https://my-website.com/debug/source/index.ts .

                                                                                                                                                                      Do not emit declarations for code that has an @internal annotation in its JSDoc comment. This is an internal compiler option; use at your own risk, because the compiler does not check that the result is valid. If you are searching for a tool to handle additional levels of visibility within your d.ts files, look at api-extractor .

                                                                                                                                                                      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

                                                                                                                                                                      With the flag set to false (default):

                                                                                                                                                                      ts
                                                                                                                                                                      /**
                                                                                                                                                                      * Days available in a week
                                                                                                                                                                      * @internal
                                                                                                                                                                      */
                                                                                                                                                                      export declare const daysInAWeek = 7;
                                                                                                                                                                      /** Calculate how much someone earns in a week */
                                                                                                                                                                      export declare function weeklySalary(dayRate: number): number;
                                                                                                                                                                       
                                                                                                                                                                      Try

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

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

                                                                                                                                                                      The JavaScript output is still the same.

                                                                                                                                                                      • Internal

                                                                                                                                                                        # JavaScript Support

                                                                                                                                                                        # 允许 JS - allowJs

                                                                                                                                                                        允许 JavaScript 文件在你的工程中被引入,而不是仅仅允许 .ts .tsx 文件。例如这个 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 工程中。

                                                                                                                                                                        • Related:
                                                                                                                                                                          • checkJs

                                                                                                                                                                          • emitDeclarationOnly

                                                                                                                                                                          • Released:

                                                                                                                                                                            1.8

                                                                                                                                                                            # 检查 JS - checkJs

                                                                                                                                                                            allowJs 配合使用,当 checkJs 被启用时,JavaScript 文件中会报告错误。也就是相当于在项目中所有 JavaScript 文件顶部包含 // @ts-check

                                                                                                                                                                            例如,根据 TypeScript 自带的 parseFloat 类型定义,这是不正确的 JavaScript:

                                                                                                                                                                            js
                                                                                                                                                                            // parseFloat 仅接受一个字符串作为参数
                                                                                                                                                                            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
                                                                                                                                                                            module.exports.pi = parseFloat(3.124);
                                                                                                                                                                            Argument of type 'number' is not assignable to parameter of type 'string'.2345Argument of type 'number' is not assignable to parameter of type 'string'.
                                                                                                                                                                             
                                                                                                                                                                            // @filename: index.ts
                                                                                                                                                                            import { pi } from "./constants";
                                                                                                                                                                            console.log(pi);
                                                                                                                                                                            Try
                                                                                                                                                                            • Related:
                                                                                                                                                                              • allowJs

                                                                                                                                                                              • emitDeclarationOnly

                                                                                                                                                                              • Released:

                                                                                                                                                                                2.3

                                                                                                                                                                                # Max Node Module JS Depth - maxNodeModuleJsDepth

                                                                                                                                                                                The maximum dependency depth to search under node_modules and load JavaScript files.

                                                                                                                                                                                This flag can only be used when allowJs is enabled, and is used if you want to have TypeScript infer types for all of the JavaScript inside your node_modules .

                                                                                                                                                                                Ideally this should stay at 0 (the default), and d.ts files should be used to explicitly define the shape of modules. However, there are cases where you may want to turn this on at the expense of speed and potential accuracy.

                                                                                                                                                                                可在编辑器内运行的语言服务插件列表。

                                                                                                                                                                                语言服务插件是一种基于现有 TypeScript 文件向用户提供额外信息的方法。它们可以改进 TypeScript 和编辑器之间的现有信息,或提供自己的错误信息。

                                                                                                                                                                              • ts-sql-plugin — 增加了用模板字符串做 SQL 构建器时的风格检查。
                                                                                                                                                                              • typescript-styled-plugin — 在目标字符串中提供 CSS 风格检查。
                                                                                                                                                                              • typescript-eslint-language-service — 在编译器的输出中提供 eslint 的错误信息和修复信息。
                                                                                                                                                                              • ts-graphql-plugin — 在 GraphQL 查询目标字符串中提供验证和补全。
                                                                                                                                                                              • VS Code 可以让一个扩展 自动包含语言服务插件 ,所以你可以在编辑器中运行一些插件,而不需要在 tsconfig.json 中指定他们。

                                                                                                                                                                                当设置为 true, 并且模块 没有 显式指定默认导出时, allowSyntheticDefaultImports 可以让你这样写导入:

                                                                                                                                                                              ts
                                                                                                                                                                              import React from "react";
                                                                                                                                                                              ts
                                                                                                                                                                              import * as React from "react";

                                                                                                                                                                              例如: allowSyntheticDefaultImports 不为 true 时:

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

                                                                                                                                                                              这段代码会引发一个错误,因为没有“default”对象可以导入,即使你认为应该有。 为了使用方便,Babel 这样的转译器会在没有默认导出时自动为其创建,使模块看起来更像:

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

                                                                                                                                                                              本选项不会影响 TypeScript 生成的 JavaScript,它仅对类型检查起作用。当你使用 Babel 生成额外的默认导出,从而使模块的默认导出更易用时,本选项可以让 TypeScript 的行为与 Babel 一致。

                                                                                                                                                                              • Default:

                                                                                                                                                                                true if esModuleInterop is enabled, module is system , or moduleResolution is bundler ; false otherwise.

                                                                                                                                                                              • Related:
                                                                                                                                                                                • esModuleInterop

                                                                                                                                                                                • Released:

                                                                                                                                                                                  1.8

                                                                                                                                                                                  # ES 模块互操作性 - esModuleInterop

                                                                                                                                                                                  默认情况下(未设置 `esModuleInterop` 或值为 false),TypeScript 像 ES6 模块一样对待 CommonJS/AMD/UMD。这样的行为有两个被证实的缺陷:

                                                                                                                                                                                  形如 import * as moment from "moment" 这样的命名空间导入等价于 const moment = require("moment")

                                                                                                                                                                                  形如 import moment from "moment" 这样的默认导入等价于 const moment = require("moment").default

                                                                                                                                                                                  这种错误的行为导致了这两个问题:

                                                                                                                                                                                  ES6 模块规范规定,命名空间导入( import * as x )只能是一个对象。TypeScript 把它处理成 = require("x") 的行为允许把导入当作一个可调用的函数,这样不符合规范。

                                                                                                                                                                                  虽然 TypeScript 准确实现了 ES6 模块规范,但是大多数使用 CommonJS/AMD/UMD 模块的库并没有像 TypeScript 那样严格遵守。

                                                                                                                                                                                  开启 esModuleInterop 选项将会修复 TypeScript 转译中的这两个问题。第一个问题通过改变编译器的行为来修复,第二个问题则由两个新的工具函数来解决,它们提供了确保生成的 JavaScript 兼容性的适配层:

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

                                                                                                                                                                                  esModuleInterop 未启用:

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

                                                                                                                                                                                  当启用 esModuleInterop

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

                                                                                                                                                                                  :你可以通过启用 importHelpers 来让 JS 输出更紧凑:

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

                                                                                                                                                                                  当启用 esModuleInterop 时,将同时启用 allowSyntheticDefaultImports

                                                                                                                                                                                  • Recommended
                                                                                                                                                                                  • Default:

                                                                                                                                                                                    true if module is node16 or nodenext ; false otherwise.

                                                                                                                                                                                  • Related:
                                                                                                                                                                                    • allowSyntheticDefaultImports

                                                                                                                                                                                    • Released:

                                                                                                                                                                                      2.7

                                                                                                                                                                                      # Force Consistent Casing In File Names - forceConsistentCasingInFileNames

                                                                                                                                                                                      TypeScript follows the case sensitivity rules of the file system it’s running on. This can be problematic if some developers are working in a case-sensitive file system and others aren’t. If a file attempts to import fileManager.ts by specifying ./FileManager.ts the file will be found in a case-insensitive file system, but not on a case-sensitive file system.

                                                                                                                                                                                      When this option is set, TypeScript will issue an error if a program tries to include a file by a casing different from the casing on disk.

                                                                                                                                                                                      • Recommended
                                                                                                                                                                                      • Default:

                                                                                                                                                                                        true

                                                                                                                                                                                        # 孤立模块 - isolatedModules

                                                                                                                                                                                        虽然你可以使用 TypeScript 来从 TypeScript 中生成 JavaScript 代码,但是使用其他转译器例如 Babel 也很常见。 但其他转译器一次只能在一个文件上操作,这意味着它们不能进行基于完全理解类型系统后的代码转译。 这个限制也同样适用于被一些构建工具使用的 TypeScript 的 ts.transpileModule 接口。

                                                                                                                                                                                        这些限制可能会导致一些 TypeScript 特性的运行时问题,例如 const enum namespace 。 设置 isolatedModules 选项后,TypeScript 将会在当你写的某些代码不能被单文件转译的过程正确处理时警告你。

                                                                                                                                                                                        它不会改变你代码的行为,也不会影响 TypeScript 的检查和代码生成过程。

                                                                                                                                                                                        一些当 isolatedModules 被启用时不工作的例子:

                                                                                                                                                                                        导出非值标识符

                                                                                                                                                                                        在 TypeScript 中,你可以引入一个 类型 ,然后再将其导出:

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

                                                                                                                                                                                        由于 someType 并没有值,所以生成的 export 将不会导出它(否则将导致 JavaScript 运行时的错误):

                                                                                                                                                                                        js
                                                                                                                                                                                        export { someFunction };

                                                                                                                                                                                        单文件转译器并不知道 someType 是否会产生一个值,所以导出一个只指向类型的名称会是一个错误。

                                                                                                                                                                                        非模块文件

                                                                                                                                                                                        如果设置了 isolatedModules ,则所有的实现文件必须是 模块 (也就是它有某种形式的 import / export )。如果任意文件不是模块就会发生错误:

                                                                                                                                                                                        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="..." /> 指令都相对于符号链接所在的位置进行解析,而不是相对于符号链接解析后的路径。

                                                                                                                                                                                        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 import s and export s 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
                                                                                                                                                                                        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 .

                                                                                                                                                                                        In prior versions of TypeScript, this controlled what encoding was used when reading text files from disk. Today, TypeScript assumes UTF-8 encoding, but will correctly detect UTF-16 (BE and LE) or UTF-8 BOMs.

                                                                                                                                                                                        • Deprecated
                                                                                                                                                                                        • Default:

                                                                                                                                                                                          utf8

                                                                                                                                                                                          # Keyof Strings Only - keyofStringsOnly

                                                                                                                                                                                          This flag changes the keyof type operator to return string instead of string | number when applied to a type with a string index signature.

                                                                                                                                                                                          This flag is used to help people keep this behavior from before TypeScript 2.9’s release .

                                                                                                                                                                                          • Deprecated
                                                                                                                                                                                          • Released:

                                                                                                                                                                                            2.9

                                                                                                                                                                                            # No Implicit Use Strict - noImplicitUseStrict

                                                                                                                                                                                            You shouldn’t need this. By default, when emitting a module file to a non-ES6 target, TypeScript emits a "use strict"; prologue at the top of the file. This setting disables the prologue.

                                                                                                                                                                                            TypeScript will unify type parameters when comparing two generic functions.

                                                                                                                                                                                            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

                                                                                                                                                                                            This flag can be used to remove that check.

                                                                                                                                                                                            • Released:

                                                                                                                                                                                              2.4

                                                                                                                                                                                              # Out - out

                                                                                                                                                                                              Use outFile instead.

                                                                                                                                                                                              The out option computes the final file location in a way that is not predictable or consistent. This option is retained for backward compatibility only and is deprecated.

                                                                                                                                                                                              • Deprecated
                                                                                                                                                                                              • Related:
                                                                                                                                                                                                • outDir

                                                                                                                                                                                                • outFile

                                                                                                                                                                                                  # Suppress Excess Property Errors - suppressExcessPropertyErrors

                                                                                                                                                                                                  This disables reporting of excess property errors, such as the one shown in the following example:

                                                                                                                                                                                                  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

                                                                                                                                                                                                  This flag was added to help people migrate to the stricter checking of new object literals in TypeScript 1.6 .

                                                                                                                                                                                                  We don’t recommend using this flag in a modern codebase, you can suppress one-off cases where you need it using // @ts-ignore .

                                                                                                                                                                                                  Turning suppressImplicitAnyIndexErrors on suppresses reporting the error about implicit anys when indexing into objects, as shown in the following example:

                                                                                                                                                                                                  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

                                                                                                                                                                                                  Using suppressImplicitAnyIndexErrors is quite a drastic approach. It is recommended to use a @ts-ignore comment instead:

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

                                                                                                                                                                                                      # Language and Environment

                                                                                                                                                                                                      # Emit Decorator Metadata - emitDecoratorMetadata

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

                                                                                                                                                                                                      For example, here is the TypeScript

                                                                                                                                                                                                      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

                                                                                                                                                                                                      With emitDecoratorMetadata not set to true (default) the emitted JavaScript is:

                                                                                                                                                                                                      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) {
                                                                                                                                                                                                      // do nothing
                                                                                                                                                                                                      }
                                                                                                                                                                                                      }
                                                                                                                                                                                                      __decorate([
                                                                                                                                                                                                      LogMethod
                                                                                                                                                                                                      ], Demo.prototype, "foo", null);
                                                                                                                                                                                                      const demo = new Demo();
                                                                                                                                                                                                       
                                                                                                                                                                                                      Try

                                                                                                                                                                                                      With emitDecoratorMetadata set to true the emitted JavaScript is:

                                                                                                                                                                                                      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) {
                                                                                                                                                                                                      // do nothing
                                                                                                                                                                                                      }
                                                                                                                                                                                                      }
                                                                                                                                                                                                      __decorate([
                                                                                                                                                                                                      LogMethod,
                                                                                                                                                                                                      __metadata("design:type", Function),
                                                                                                                                                                                                      __metadata("design:paramtypes", [Number]),
                                                                                                                                                                                                      __metadata("design:returntype", void 0)
                                                                                                                                                                                                      ], Demo.prototype, "foo", null);
                                                                                                                                                                                                      const demo = new Demo();
                                                                                                                                                                                                       
                                                                                                                                                                                                      Try
                                                                                                                                                                                                      • Related:
                                                                                                                                                                                                        • experimentalDecorators

                                                                                                                                                                                                          # Experimental Decorators - experimentalDecorators

                                                                                                                                                                                                          Enables experimental support for decorators , which is a version of decorators that predates the TC39 standardization process.

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

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

                                                                                                                                                                                                          • Related:
                                                                                                                                                                                                            • emitDecoratorMetadata

                                                                                                                                                                                                              # JSX - jsx

                                                                                                                                                                                                              控制 JSX 在 JavaScript 文件中的输出方式。 这只影响 .tsx 文件的 JS 文件输出。

                                                                                                                                                                                                            • react : 将 JSX 改为等价的对 React.createElement 的调用并生成 .js 文件。
                                                                                                                                                                                                            • react-jsx : 改为 __jsx 调用并生成 .js 文件。
                                                                                                                                                                                                            • react-jsxdev : 改为 __jsx 调用并生成 .js 文件。
                                                                                                                                                                                                            • preserve : 不对 JSX 进行改变并生成 .jsx 文件。
                                                                                                                                                                                                            • react-native : 不对 JSX 进行改变并生成 .js 文件。
                                                                                                                                                                                                            • 示例代码:

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

                                                                                                                                                                                                            默认为: "react"

                                                                                                                                                                                                            tsx
                                                                                                                                                                                                            import React from 'react';
                                                                                                                                                                                                            export const helloWorld = () => React.createElement("h1", null, "Hello world");
                                                                                                                                                                                                             
                                                                                                                                                                                                            Try

                                                                                                                                                                                                            保留: "preserve"

                                                                                                                                                                                                            tsx
                                                                                                                                                                                                            import React from 'react';
                                                                                                                                                                                                            export const helloWorld = () => <h1>Hello world</h1>;
                                                                                                                                                                                                             
                                                                                                                                                                                                            Try

                                                                                                                                                                                                            React Native: "react-native"

                                                                                                                                                                                                            tsx
                                                                                                                                                                                                            import React from 'react';
                                                                                                                                                                                                            export const helloWorld = () => <h1>Hello world</h1>;
                                                                                                                                                                                                             
                                                                                                                                                                                                            Try

                                                                                                                                                                                                            React 17 转换: "react-jsx" [1]

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

                                                                                                                                                                                                            React 17 开发模式转换: "react-jsxdev" [1]

                                                                                                                                                                                                            tsx
                                                                                                                                                                                                            import { jsxDEV as _jsxDEV } from "react/jsx-dev-runtime";
                                                                                                                                                                                                            const _jsxFileName = "/vercel/path0/packages/typescriptlang-org/index.tsx";
                                                                                                                                                                                                            export const helloWorld = () => _jsxDEV("h1", { children: "Hello world" }, void 0, false, { fileName: _jsxFileName, lineNumber: 9, columnNumber: 32 }, this);
                                                                                                                                                                                                             
                                                                                                                                                                                                            Try
                                                                                                                                                                                                            • Allowed:
                                                                                                                                                                                                              • preserve

                                                                                                                                                                                                              • react

                                                                                                                                                                                                              • react-native

                                                                                                                                                                                                              • react-jsx

                                                                                                                                                                                                              • react-jsxdev

                                                                                                                                                                                                              • Related:
                                                                                                                                                                                                                • jsxFactory

                                                                                                                                                                                                                • jsxFragmentFactory

                                                                                                                                                                                                                • jsxImportSource

                                                                                                                                                                                                                • Released:

                                                                                                                                                                                                                  2.2

                                                                                                                                                                                                                  # JSX Factory - jsxFactory

                                                                                                                                                                                                                  Changes the function called in .js files when compiling JSX Elements using the classic JSX runtime. The most common change is to use "h" or "preact.h" instead of the default "React.createElement" if using preact .

                                                                                                                                                                                                                  For example, this TSX file:

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

                                                                                                                                                                                                                  With jsxFactory: "h" looks like:

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

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

                                                                                                                                                                                                                  tsx
                                                                                                                                                                                                                  /** @jsx h */
                                                                                                                                                                                                                  import { h } from "preact";
                                                                                                                                                                                                                  Cannot find module 'preact' or its corresponding type declarations.2307Cannot find module 'preact' or its corresponding type declarations.
                                                                                                                                                                                                                   
                                                                                                                                                                                                                  const HelloWorld = () => <div>Hello</div>;
                                                                                                                                                                                                                  Try

                                                                                                                                                                                                                  The factory chosen will also affect where the JSX namespace is looked up (for type checking information) before falling back to the global one.

                                                                                                                                                                                                                  If the factory is defined as React.createElement (the default), the compiler will check for React.JSX before checking for a global JSX . If the factory is defined as h , it will check for h.JSX before a global JSX .

                                                                                                                                                                                                                  • Default:

                                                                                                                                                                                                                    React.createElement

                                                                                                                                                                                                                  • Allowed:
                                                                                                                                                                                                                    • Any identifier or dotted identifier.

                                                                                                                                                                                                                    • Related:
                                                                                                                                                                                                                      • jsx

                                                                                                                                                                                                                      • jsxFragmentFactory

                                                                                                                                                                                                                      • jsxImportSource

                                                                                                                                                                                                                        # JSX Fragment Factory - jsxFragmentFactory

                                                                                                                                                                                                                        Specify the JSX fragment factory function to use when targeting react JSX emit with jsxFactory compiler option is specified, e.g. Fragment .

                                                                                                                                                                                                                        For example with this TSConfig:

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

                                                                                                                                                                                                                        This TSX file:

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

                                                                                                                                                                                                                        Would look like:

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

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

                                                                                                                                                                                                                        For example:

                                                                                                                                                                                                                        tsx
                                                                                                                                                                                                                        /** @jsx h */
                                                                                                                                                                                                                        /** @jsxFrag Fragment */
                                                                                                                                                                                                                         
                                                                                                                                                                                                                        import { h, Fragment } from "preact";
                                                                                                                                                                                                                        Cannot find module 'preact' or its corresponding type declarations.2307Cannot find module 'preact' or its corresponding type declarations.
                                                                                                                                                                                                                         
                                                                                                                                                                                                                        const HelloWorld = () => (
                                                                                                                                                                                                                        <>
                                                                                                                                                                                                                        <div>Hello</div>
                                                                                                                                                                                                                        </>
                                                                                                                                                                                                                        );
                                                                                                                                                                                                                        Try
                                                                                                                                                                                                                        • Default:

                                                                                                                                                                                                                          React.Fragment

                                                                                                                                                                                                                        • Related:
                                                                                                                                                                                                                          • jsx

                                                                                                                                                                                                                          • jsxFactory

                                                                                                                                                                                                                          • jsxImportSource

                                                                                                                                                                                                                          • Released:

                                                                                                                                                                                                                            4.0

                                                                                                                                                                                                                            # JSX Import Source - jsxImportSource

                                                                                                                                                                                                                            Declares the module specifier to be used for importing the jsx and jsxs factory functions when using jsx as "react-jsx" or "react-jsxdev" which were introduced in TypeScript 4.1.

                                                                                                                                                                                                                            With React 17 the library supports a new form of JSX transformation via a separate import.

                                                                                                                                                                                                                            For example with this code:

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

                                                                                                                                                                                                                            Using this TSConfig:

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

                                                                                                                                                                                                                            The emitted JavaScript from TypeScript is:

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

                                                                                                                                                                                                                            For example if you wanted to use "jsxImportSource": "preact" , you need a tsconfig like:

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

                                                                                                                                                                                                                            Which generates code like:

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

                                                                                                                                                                                                                            Alternatively, you can use a per-file pragma to set this option, for example:

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

                                                                                                                                                                                                                            Would add preact/jsx-runtime as an import for the _jsx factory.

                                                                                                                                                                                                                            Note: In order for this to work like you would expect, your tsx file must include an export or import so that it is considered a module.

                                                                                                                                                                                                                            • Default:

                                                                                                                                                                                                                              react

                                                                                                                                                                                                                            • Related:
                                                                                                                                                                                                                              • jsx

                                                                                                                                                                                                                              • jsxFactory

                                                                                                                                                                                                                              • Released:

                                                                                                                                                                                                                                4.1

                                                                                                                                                                                                                                # 库 - lib

                                                                                                                                                                                                                                TypeScript 包括一组默认的内建 JS 接口(例如 Math )的类型定义,以及在浏览器环境中存在的对象的类型定义(例如 document )。 TypeScript 还包括与你指定的 target 选项相匹配的较新的 JS 特性的 API。例如如果 target ES6 或更新的环境,那么 Map 的类型定义是可用的。

                                                                                                                                                                                                                                你可能出于某些原因改变这些:

                                                                                                                                                                                                                              • 你的程序不运行在浏览器中,因此你不想要 "dom" 类型定义。
                                                                                                                                                                                                                              • 你的运行时平台提供了某些 JavaScript API 对象(也许通过 polyfill),但还不支持某个 ECMAScript 版本的完整语法。
                                                                                                                                                                                                                              • 你有一些 (但不是全部)对于更高级别的 ECMAScript 版本的 polyfill 或本地实现。
                                                                                                                                                                                                                              • ES2015 ES2015 中额外提供的 API (又被称为 ES6) —— array.find Promise Proxy Symbol Map Set Reflect 等。 ES2015 的别名。 ES2016 ES2016 中额外提供的 API —— array.include 等。 ES2016 的别名。 ES2017 ES2017 中额外提供的 API —— Object.entries Object.values Atomics SharedArrayBuffer date.formatToParts typed arrays 等。 ES2018 ES2018 中额外提供的 API —— async iterables promise.finally Intl.PluralRules rexexp.groups 等。 ES2019 ES2019 中额外提供的 API —— array.flat array.flatMap Object.fromEntries string.trimStart string.trimEnd 等。 ES2020 ES2020 中额外提供的 API —— string.matchAll 等。 ESNext ESNext 中额外提供的 API —— 随着 JavaScript 的发展,这些会发生变化。 DOM 定义 —— window document 等。 WebWorker WebWorker 上下文中存在的 API。 ScriptHost Windows Script Hosting System 的 API。

                                                                                                                                                                                                                                库的各个组件

                                                                                                                                                                                                                                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

                                                                                                                                                                                                                                  • force

                                                                                                                                                                                                                                  • Released:

                                                                                                                                                                                                                                    4.7

                                                                                                                                                                                                                                    # No Lib - noLib

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

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

                                                                                                                                                                                                                                    • Related:
                                                                                                                                                                                                                                      • lib

                                                                                                                                                                                                                                        # React Namespace - reactNamespace

                                                                                                                                                                                                                                        Use jsxFactory instead. Specify the object invoked for createElement when targeting react for TSX files.

                                                                                                                                                                                                                                        • Default:

                                                                                                                                                                                                                                          React

                                                                                                                                                                                                                                          # 编译目标 - target

                                                                                                                                                                                                                                          现代浏览器支持全部 ES6 的功能,所以 ES6 是一个不错的选择。 如果你的代码部署在旧的环境中,你可以选择设置一个更低的目标;如果你的代码保证会运行在新的环境中,你可以选择一个更高的目标。

                                                                                                                                                                                                                                          target 的配置将会改变哪些 JS 特性会被降级,而哪些会被完整保留 例如,如果 target 是 ES5 或更低版本,箭头函数 () => this 会被转换为等价的 函数 表达式。

                                                                                                                                                                                                                                          改变 target 也会改变 lib 选项的默认值。 你可以根据需要混搭 target lib 的配置,你也可以为了方便只设置 target

                                                                                                                                                                                                                                          如果你只使用 Node.js,这里推荐基于 Node 版本的 target

                                                                                                                                                                                                                                          支持的编译目标

                                                                                                                                                                                                                                          这些基于 node.green 的支持数据库。

                                                                                                                                                                                                                                          特殊的 ESNext 值代表你的 TypeScript 所支持的最高版本。这个配置应当被谨慎使用,因为它在不同的 TypeScript 版本之间的含义不同,并且会导致升级更难预测。

                                                                                                                                                                                                                                          • Default:

                                                                                                                                                                                                                                            ES3

                                                                                                                                                                                                                                          • Allowed:
                                                                                                                                                                                                                                            • es3

                                                                                                                                                                                                                                            • es6 / es2015

                                                                                                                                                                                                                                            • es2016

                                                                                                                                                                                                                                            • es2017

                                                                                                                                                                                                                                            • es2018

                                                                                                                                                                                                                                            • es2019

                                                                                                                                                                                                                                            • es2020

                                                                                                                                                                                                                                            • es2021

                                                                                                                                                                                                                                            • es2022

                                                                                                                                                                                                                                            • esnext

                                                                                                                                                                                                                                            • Released:

                                                                                                                                                                                                                                              1.0

                                                                                                                                                                                                                                              # Use Define For Class Fields - useDefineForClassFields

                                                                                                                                                                                                                                              This flag is used as part of migrating to the upcoming standard version of class fields. TypeScript introduced class fields many years before it was ratified in TC39. The latest version of the upcoming specification has a different runtime behavior to TypeScript’s implementation but the same syntax.

                                                                                                                                                                                                                                              This flag switches to the upcoming ECMA runtime behavior.

                                                                                                                                                                                                                                              You can read more about the transition in the 3.7 release notes .

                                                                                                                                                                                                                                              • Default:

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

                                                                                                                                                                                                                                              • Released:

                                                                                                                                                                                                                                                3.7

                                                                                                                                                                                                                                                # Compiler Diagnostics

                                                                                                                                                                                                                                                # Diagnostics - diagnostics

                                                                                                                                                                                                                                                Used to output diagnostic information for debugging. This command is a subset of extendedDiagnostics which are more user-facing results, and easier to interpret.

                                                                                                                                                                                                                                                If you have been asked by a TypeScript compiler engineer to give the results using this flag in a compile, in which there is no harm in using extendedDiagnostics instead.

                                                                                                                                                                                                                                                • Deprecated
                                                                                                                                                                                                                                                • Related:
                                                                                                                                                                                                                                                  • 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.

                                                                                                                                                                                                                                                    • Released:

                                                                                                                                                                                                                                                      4.2

                                                                                                                                                                                                                                                      # Extended Diagnostics - extendedDiagnostics

                                                                                                                                                                                                                                                      You can use this flag to discover where TypeScript is spending its time when compiling. This is a tool used for understanding the performance characteristics of your codebase overall.

                                                                                                                                                                                                                                                      You can learn more about how to measure and understand the output in the performance section of the wiki .

                                                                                                                                                                                                                                                      • Related:
                                                                                                                                                                                                                                                        • diagnostics

                                                                                                                                                                                                                                                          # Generate CPU Profile - generateCpuProfile

                                                                                                                                                                                                                                                          This option gives you the chance to have TypeScript emit a v8 CPU profile during the compiler run. The CPU profile can provide insight into why your builds may be slow.

                                                                                                                                                                                                                                                          This option can only be used from the CLI via: --generateCpuProfile tsc-output.cpuprofile .

                                                                                                                                                                                                                                                          sh