編譯器選項

頂級選項
  1. files,
  2. extends,
  3. include,
  4. exclude 以及
  5. references

"compilerOptions"

JavaScript 支援
  1. allowJs,
  2. checkJs 以及
  3. maxNodeModuleJsDepth
編輯器支援
  1. disableSizeLimit 以及
  2. plugins
命令列

    根欄位

    TSConfig 中的根選項用於配置 TypeScript 或 JavaScript 專案的設定方式。

    # 檔案列表 - files

    指定包含在程式中的檔案白名單。如果找不到任何指定檔案,將報錯。

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

    當專案檔案數量很少且無需使用萬用字元引用大量檔案時,該選項很有用。如果需要萬用字元,請使用 include

    • 預設值

      false

    • 相關選項
      • include

      • exclude

    • 釋出版本

      1.5

    # 繼承 - extends

    extends 的值是一個字串,包含指向另一個配置檔案的路徑,以進行繼承。該路徑可以使用 Node.js 風格的解析方式。

    基礎檔案中的配置先載入,然後被繼承配置中的設定覆蓋。配置檔案中的所有相對路徑將相對於它們所屬的配置檔案進行解析。

    值得注意的是,繼承配置中的 filesincludeexclude覆蓋基礎配置中的同名設定,且不允許配置檔案之間存在迴圈引用。

    目前,唯一不參與繼承的頂級屬性是 references

    示例

    configs/base.json:

    tsconfig.json:

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

    tsconfig.nostrictnull.json:

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

    配置檔案中包含的非繼承排除的相對路徑屬性,將相對於它們所屬的配置檔案進行解析。

    • 預設值

      false

    • 釋出版本

      2.1

    # 包含 - include

    指定一個檔名或模式陣列,以包含在程式中。這些檔名相對於包含 tsconfig.json 檔案的目錄進行解析。

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

    這將包含

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

    includeexclude 支援萬用字元以建立 Glob 模式

    • * 匹配零個或多個字元(不包括目錄分隔符)
    • ? 匹配任意單個字元(不包括目錄分隔符)
    • **/ 匹配任何層級的巢狀目錄

    如果模式的最後一個路徑段不包含副檔名或萬用字元,則將其視為目錄,幷包含該目錄中支援副檔名的檔案(例如,預設支援 .ts.tsx.d.ts,如果 allowJs 設定為 true,則還支援 .js.jsx)。

    • 預設值

      [](如果指定了 files);否則為 **/*

    • 相關選項
      • files

      • exclude

    • 釋出版本

      2.0

    # 排除 - exclude

    指定一個檔名或模式陣列,在解析 include 時應跳過這些檔案。

    重要提示exclude 改變因 include 設定而包含的檔案。透過 exclude 指定的檔案仍可能因程式碼中的 import 語句、types 包含、/// <reference 指令或在 files 列表中指定而成為程式碼庫的一部分。

    它並不是阻止檔案被包含在程式碼庫中的機制,它只是改變 include 設定的查詢結果。

    • 預設值

      node_modules bower_components jspm_packages outDir

    • 相關選項
      • include

      • files

    • 釋出版本

      2.0

    # 專案引用 - references

    專案引用是一種將 TypeScript 程式組織成更小模組的方法。使用專案引用可以顯著提高構建和編輯器響應速度,強制實現元件間的邏輯分離,並以新的改進方式組織程式碼。

    您可以在手冊的 專案引用 章節中閱讀更多關於其工作原理的內容。

    • 預設值

      false

    • 釋出版本

      3.0

    編譯器選項

    這些選項構成了 TypeScript 配置的大部分內容,涵蓋了語言的工作方式。

    #型別檢查

    # 允許無法執行的程式碼 - allowUnreachableCode

    當設定為:

    • undefined (預設) - 將無法執行的程式碼作為警告提示給編輯器
    • true - 忽略無法執行的程式碼
    • false - 對無法執行的程式碼丟擲編譯器錯誤

    這些警告僅針對由於使用了 JavaScript 語法而導致明顯無法執行的程式碼,例如

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

    設定 "allowUnreachableCode": false

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

    這不會影響基於型別分析而看似無法執行的程式碼錯誤。

    • 釋出版本

      1.8

    # 允許未使用的標籤 - allowUnusedLabels

    當設定為:

    • undefined (預設) - 將無法執行的程式碼作為警告提示給編輯器
    • true - 忽略未使用的標籤
    • false - 對未使用的標籤丟擲編譯器錯誤

    標籤在 JavaScript 中非常罕見,通常表示試圖編寫物件字面量但出錯。

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

      1.8

    # 始終嚴格模式 - alwaysStrict

    確保檔案在 ECMAScript 嚴格模式下解析,併為每個原始檔輸出 "use strict"。

    ECMAScript 嚴格模式 在 ES5 中引入,透過調整 JavaScript 引擎執行時的行為來提高效能,並將一些潛在的靜默錯誤改為丟擲異常。

    • 預設值

      如果設定了 strict 則為 true;否則為 false

    • 相關選項
      • strict

    • 釋出版本

      2.1

    # 精確可選屬性型別 - exactOptionalPropertyTypes

    啟用後,TypeScript 對 typeinterfaces 中帶有 ? 字首的屬性的處理將應用更嚴格的規則。

    例如,此介面聲明瞭一個屬性,該屬性可以是 'dark' 或 'light' 兩個字串之一,或者該屬性不應該存在於物件中。

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

    如果不啟用此標誌,您可以將 colorThemeOverride 設定為三個值: “dark”、“light” 和 undefined

    將值設定為 undefined 會導致大多數 JavaScript 執行時檢查失敗,因為它本質上是 falsy 值。然而,這並不完全準確;colorThemeOverride: undefined 與屬性 colorThemeOverride 未定義並不相同。例如,在設定中使用 "colorThemeOverride" in settings 時,undefined 作為鍵的行為與未定義完全不同。

    exactOptionalPropertyTypes 讓 TypeScript 真正強制執行可選屬性的定義。

    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
    • 推薦
    • 釋出版本

      4.4

    # 不允許 Switch 語句貫穿 - noFallthroughCasesInSwitch

    報告 switch 語句中貫穿 (fallthrough) 情況的錯誤。確保 switch 語句中任何非空的 case 都包含 breakreturnthrow。這意味著您不會意外引入 case 貫穿錯誤。

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

      1.8

    # 禁止隱式 Any - noImplicitAny

    在某些情況下,如果沒有型別註解,當 TypeScript 無法推斷變數型別時,它會回退到 any 型別。

    這可能導致某些錯誤被漏掉,例如

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

    開啟 noImplicitAny 後,每當 TypeScript 本應推斷為 any 時,它都會丟擲錯誤。

    ts
    function fn(s) {
    Parameter 's' implicitly has an 'any' type.7006Parameter 's' implicitly has an 'any' type.
    console.log(s.subtr(3));
    }
    Try
    • 推薦
    • 預設值

      如果設定了 strict 則為 true;否則為 false

    • 相關選項
      • strict

    • 釋出版本

      1.0

    # 禁止隱式重寫 - noImplicitOverride

    在使用繼承的類時,如果基類中的函式重新命名,子類過載的函式可能會變得“不同步”。

    例如,假設您正在模擬一個音樂專輯同步系統

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

    當您新增對機器學習生成播放列表的支援時,您將 Album 類重構為擁有一個 'setup' 函式

    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

    在這種情況下,TypeScript 沒有提供警告,提示 SharedAlbum 上的 download 預期會重寫基類中的函式。

    使用 noImplicitOverride,您可以確保重寫函式時包含 override 關鍵字,從而使子類始終保持同步。

    以下示例啟用了 noImplicitOverride,您可以看到缺少 override 時收到的錯誤

    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
    • 釋出版本

      4.3

    # 禁止隱式返回 - noImplicitReturns

    啟用後,TypeScript 將檢查函式中的所有程式碼路徑,以確保它們都有返回值。

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

      1.8

    # 禁止隱式 This - noImplicitThis

    當 'this' 表示式具有隱式的 'any' 型別時觸發錯誤。

    例如,下面的類返回一個試圖訪問 this.widththis.height 的函式,但 getAreaFunction 內部函式的 this 上下文不是 Rectangle 的例項。

    ts
    class Rectangle {
    width: number;
    height: number;
     
    constructor(width: number, height: number) {
    this.width = width;
    this.height = height;
    }
     
    getAreaFunction() {
    return function () {
    return this.width * this.height;
    'this' implicitly has type 'any' because it does not have a type annotation.
    'this' implicitly has type 'any' because it does not have a type annotation.
    2683
    2683
    'this' implicitly has type 'any' because it does not have a type annotation.
    'this' implicitly has type 'any' because it does not have a type annotation.
    };
    }
    }
    Try
    • 推薦
    • 預設值

      如果設定了 strict 則為 true;否則為 false

    • 相關選項
      • strict

    • 釋出版本

      2.0

    # 禁止索引簽名屬性訪問 - noPropertyAccessFromIndexSignature

    此設定確保透過“點”語法 (obj.key) 訪問欄位與“索引”語法 (obj["key"]) 以及屬性在型別中的宣告方式保持一致。

    如果不使用此標誌,TypeScript 允許使用點語法訪問未定義的欄位

    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

    開啟此標誌後,由於未知欄位使用了點語法而不是索引語法,將觸發錯誤。

    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

    此標誌的目標是在呼叫語法中表明您對於該屬性是否存在的確定程度。

    • 釋出版本

      4.2

    # 禁止未檢查的索引訪問 - noUncheckedIndexedAccess

    TypeScript 透過索引簽名來描述具有未知鍵但具有已知值型別的物件。

    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

    開啟 noUncheckedIndexedAccess 會將 undefined 新增到型別中任何未宣告的欄位中。

    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
    • 釋出版本

      4.1

    # 禁止未使用的區域性變數 - noUnusedLocals

    報告未使用的區域性變數錯誤。

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

      2.0

    # 禁止未使用的引數 - noUnusedParameters

    報告函式中未使用的引數錯誤。

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

    名稱以下劃線 (_) 開頭的引數宣告免於未使用的引數檢查。例如:

    ts
    const createDefaultKeyboard = (_modelID: number) => {
    return { type: "keyboard" };
    };
    Try
    • 釋出版本

      2.0

    # 嚴格模式 - strict

    strict 標誌啟用了廣泛的型別檢查行為,從而對程式的正確性提供了更強的保證。開啟此選項等同於啟用下面概述的所有“嚴格模式系列”選項。之後,您可以根據需要關閉特定的嚴格模式系列檢查。

    未來的 TypeScript 版本可能會在此標誌下引入更嚴格的檢查,因此升級 TypeScript 可能會導致您的程式中出現新的型別錯誤。在適當且可能的情況下,將會新增相應的標誌來停用這些行為。

    • 推薦
    • 預設值

      true

    • 相關選項
      • alwaysStrict

      • strictNullChecks

      • strictBindCallApply

      • strictBuiltinIteratorReturn

      • strictFunctionTypes

      • strictPropertyInitialization

      • noImplicitAny

      • noImplicitThis

      • useUnknownInCatchVariables

    • 釋出版本

      2.3

    # 嚴格 Bind/Call/Apply 檢查 - strictBindCallApply

    設定後,TypeScript 將檢查函式內建的 callbindapply 方法呼叫時所傳入的引數是否符合底層函式的定義。

    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

    否則,這些函式接受任何引數並返回 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
    • 推薦
    • 預設值

      如果設定了 strict 則為 true;否則為 false

    • 相關選項
      • strict

    • 釋出版本

      3.2

    # 嚴格內建迭代器返回 - strictBuiltinIteratorReturn

    內建迭代器的 TReturn 型別被例項化為 undefined 而不是 any
    • 推薦
    • 預設值

      如果設定了 strict 則為 true;否則為 false

    • 相關選項
      • strict

    • 釋出版本

      5.6

    # 嚴格函式型別 - strictFunctionTypes

    啟用後,此標誌會導致函式引數檢查更加正確。

    以下是 strictFunctionTypes 關閉時的基本示例

    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

    strictFunctionTypes 開啟 時,錯誤會被正確檢測到

    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

    在此功能的開發過程中,我們發現了大量本質上不安全的類層次結構,包括 DOM 中的一些結構。因此,該設定僅適用於以 function 語法編寫的函式,而不適用於以 method 語法編寫的函式。

    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
    • 推薦
    • 預設值

      如果設定了 strict 則為 true;否則為 false

    • 相關選項
      • strict

    • 釋出版本

      2.6

    # 嚴格空值檢查 - strictNullChecks

    strictNullChecksfalse 時,語言會有效地忽略 nullundefined。這可能導致執行時出現意外錯誤。

    strictNullCheckstrue 時,nullundefined 具有自己獨特的型別,如果您試圖在需要具體值的地方使用它們,將會得到型別錯誤。

    例如,對於此 TypeScript 程式碼,users.find 無法保證一定能找到使用者,但您可以像它一定會找到一樣編寫程式碼。

    ts
    declare const loggedInUsername: string;
     
    const users = [
    { name: "Oby", age: 12 },
    { name: "Heera", age: 32 },
    ];
     
    const loggedInUser = users.find((u) => u.name === loggedInUsername);
    console.log(loggedInUser.age);
    Try

    strictNullChecks 設定為 true 將會報錯,提示您在試圖使用 loggedInUser 之前沒有保證它確實存在。

    ts
    declare const loggedInUsername: string;
     
    const users = [
    { name: "Oby", age: 12 },
    { name: "Heera", age: 32 },
    ];
     
    const loggedInUser = users.find((u) => u.name === loggedInUsername);
    console.log(loggedInUser.age);
    'loggedInUser' is possibly 'undefined'.18048'loggedInUser' is possibly 'undefined'.
    Try

    第二個示例失敗是因為陣列的 find 函式看起來有點像這個簡化版

    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;
    };
    • 推薦
    • 預設值

      如果設定了 strict 則為 true;否則為 false

    • 相關選項
      • strict

    • 釋出版本

      2.0

    # 嚴格屬性初始化 - strictPropertyInitialization

    設定為 true 時,如果類屬性被宣告但未在建構函式中初始化,TypeScript 將丟擲錯誤。

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

    在上述情況下

    • this.name 已明確設定。
    • this.accountType 有預設值。
    • this.email 未設定,丟擲錯誤。
    • this.address 被宣告為可能為 undefined,這意味著不需要顯式設定。
    • 推薦
    • 預設值

      如果設定了 strict 則為 true;否則為 false

    • 相關選項
      • strict

    • 釋出版本

      2.7

    # Catch 變數使用 Unknown 型別 - useUnknownInCatchVariables

    在 TypeScript 4.0 中,增加了支援,允許將 catch 子句中的變數型別從 any 更改為 unknown。從而支援如下程式碼:

    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

    這種模式確保了錯誤處理程式碼變得更加全面,因為您無法提前保證被丟擲的物件確實是 Error 的子類。開啟 useUnknownInCatchVariables 標誌後,您無需額外的語法 (: unknown) 也不需要 linter 規則來強制執行此行為。

    • 推薦
    • 預設值

      如果設定了 strict 則為 true;否則為 false

    • 相關選項
      • strict

    • 釋出版本

      4.4

    #模組

    # 允許任意副檔名 - allowArbitraryExtensions

    在 TypeScript 5.0 中,當匯入路徑以非 JavaScript 或 TypeScript 副檔名結尾時,編譯器會以 {file basename}.d.{extension}.ts 的形式查詢該路徑的宣告檔案。例如,如果您在打包專案中使用 CSS 載入器,您可能希望為這些樣式表編寫(或生成)宣告檔案。

    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

    預設情況下,此匯入會觸發錯誤,告知您 TypeScript 不理解該檔案型別,且您的執行時可能不支援匯入它。但是,如果您已配置執行時或打包器來處理它,可以使用新的 --allowArbitraryExtensions 編譯器選項禁止此錯誤。

    請注意,歷史上透過新增名為 app.css.d.ts 而不是 app.d.css.ts 的宣告檔案通常也能達到類似效果——但這僅透過 Node 的 CommonJS require 解析規則生效。嚴格來說,前者被解釋為名為 app.css.js 的 JavaScript 檔案的宣告檔案。由於相對檔案匯入在 Node 的 ESM 支援中需要包含副檔名,TypeScript 會在 --moduleResolution node16nodenext 下的 ESM 檔案中報錯。

    有關更多資訊,請查閱 此功能的提案對應的拉取請求 (PR)

    • 釋出版本

      5.0

    # 允許匯入 TS 副檔名 - allowImportingTsExtensions

    --allowImportingTsExtensions 允許 TypeScript 檔案使用特定的 TypeScript 副檔名(如 .ts.mts.tsx)相互匯入。

    此標誌僅在開啟 --noEmit--emitDeclarationOnly 時允許,因為這些匯入路徑在 JavaScript 輸出檔案中無法在執行時解析。此處的期望是,您的解析器(例如您的打包器、執行時或其他工具)將使這些 .ts 檔案之間的匯入生效。

    # 允許 UMD 全域性訪問 - allowUmdGlobalAccess

    設定為 true 時,allowUmdGlobalAccess 允許您從模組檔案內部將 UMD 匯出作為全域性變數訪問。模組檔案是具有匯入和/或匯出語句的檔案。如果沒有此標誌,使用 UMD 模組的匯出需要匯入宣告。

    此標誌的一個示例用例是 Web 專案,其中您知道某個庫(如 jQuery 或 Lodash)在執行時將始終可用,但您無法透過匯入方式訪問它。

    • 釋出版本

      3.5

    # 基準 URL - baseUrl

    設定用於解析非相對模組名稱的基目錄。例如,在目錄結構中:

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

    設定 "baseUrl": "./" 後,TypeScript 將從 tsconfig.json 所在的資料夾開始查詢檔案。

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

    此解析方式的優先順序高於從 node_modules 中查詢。

    此功能專為與瀏覽器中的 AMD 模組載入器結合使用而設計,不建議在任何其他環境中使用。從 TypeScript 4.1 開始,使用 paths 時不再強制要求設定 baseUrl

    • 釋出版本

      2.0

    # 自定義條件 - customConditions

    --customConditions 接收一個額外的 條件 (conditions) 列表,當 TypeScript 從 package.jsonexportsimports 欄位解析時,這些條件應被視為成功。這些條件會被新增到解析器預設使用的任何現有條件中。

    例如,當在 tsconfig.json 中設定該欄位如下時:

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

    每當引用 package.json 中的 exportsimports 欄位時,TypeScript 都會考慮名為 my-condition 的條件。

    因此,當從具有以下 package.json 的包匯入時:

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

    TypeScript 將嘗試查詢與 foo.mjs 對應的檔案。

    此欄位僅在 --moduleResolution 設定為 node16nodenextbundler 時有效。

    • 相關選項
      • moduleResolution

      • resolvePackageJsonExports

      • resolvePackageJsonImports

    • 釋出版本

      5.0

    # 模組系統 - module

    設定程式的模組系統。有關更多資訊,請參閱 TypeScript module 選項背後的理論其參考頁面。在現代 Node.js 專案中,您很可能需要 "nodenext",而在需要打包的程式碼中則使用 preserveesnext

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

    UMD

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

    AMD

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

    System

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

    ESNext

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

    ES2015/ES6/ES2020/ES2022

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

    除了 ES2015/ES6 的基礎功能外,ES2020 增加了對 動態 importimport.meta 的支援,而 ES2022 進一步增加了對 頂層 await 的支援。

    node16/node18/node20/nodenext

    node16node18node20nodenext 模式與 Node 的 原生 ECMAScript 模組支援 整合。輸出的 JavaScript 根據副檔名以及最近的 package.jsontype 設定的值,使用 CommonJSES2020。模組解析方式也不同。您可以在 手冊模組參考 中瞭解更多資訊。

    • node16 從 TypeScript 4.7 開始可用
    • node18 從 TypeScript 5.8 開始可用,作為 node16 的替代品,並增加了對匯入屬性的支援。
    • node20 增加了對 require(ESM) 的支援。
    • nodenext 從 TypeScript 4.7 開始可用,但其行為隨 Node.js 的最新穩定版本而變化。--module nodenext 隱含了浮動的 --target esnext

    preserve

    --module preserve(於 TypeScript 5.4 中新增)模式下,輸入檔案中編寫的 ECMAScript 匯入和匯出在輸出中被保留,CommonJS 風格的 import x = require("...")export = ... 語句被輸出為 CommonJS 的 requiremodule.exports。換句話說,每個單獨匯入或匯出語句的格式都會被保留,而不是被迫轉換為整個編譯(甚至整個檔案)統一的格式。

    ts
    import { valueOfPi } from "./constants";
    const constants = require("./constants");
    export const piSquared = valueOfPi * constants.valueOfPi;
     
    Try

    雖然在同一個檔案中混合使用 import 和 require 呼叫並不常見,但這種 module 模式最好地反映了大多數現代打包器以及 Bun 執行時的能力。

    為什麼要關心在打包器或 Bun 中使用 TypeScript 的 module 輸出,而您可能也設定了 noEmit?TypeScript 的型別檢查和模組解析行為會受到它將會輸出的模組格式的影響。設定 module 可以讓 TypeScript 瞭解您的打包器或執行時將如何處理匯入和匯出,這確保了您在匯入值上看到的型別能夠準確反映執行時或打包後的實際情況。

    None

    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
    • 預設值

      如果 targetES5,則為 CommonJS;否則為 ES6/ES2015

    • 允許的值
      • none

      • commonjs

      • amd

      • umd

      • system

      • es6/es2015

      • es2020

      • es2022

      • esnext

      • node16

      • node18

      • node20

      • nodenext

      • preserve

    • 相關選項
      • moduleResolution

      • esModuleInterop

      • allowImportingTsExtensions

      • allowArbitraryExtensions

      • resolveJsonModule

    • 釋出版本

      1.0

    # 模組解析 - moduleResolution

    指定模組解析策略

    • 'node16''nodenext' 用於現代版本的 Node.js。Node.js v12 及更高版本同時支援 ECMAScript 匯入和 CommonJS require,它們使用不同的演算法進行解析。當這些 moduleResolution 值與相應的 module 值結合使用時,會根據 Node.js 在輸出的 JavaScript 程式碼中看到的是 import 還是 require,選擇正確的演算法。
    • 'node10'(以前稱為 'node')用於 v10 之前的 Node.js 版本,這些版本僅支援 CommonJS require。您可能不需要在現代程式碼中使用 node10
    • 'bundler' 用於配合打包器使用。像 node16nodenext 一樣,此模式支援 package.json 的 "imports""exports",但與 Node.js 解析模式不同,bundler 在匯入的相對路徑上從不要求副檔名。
    • 'classic' 在 1.6 版本釋出之前被 TypeScript 使用。不應再使用 classic

    有參考頁面解釋了 TypeScript 模組解析背後的理論 以及 每個選項的詳細資訊

    • 預設值

      如果 moduleCommonJS,則為 Node10;如果 moduleNode16Node18Node20,則為 Node16;如果 moduleNodeNext,則為 NodeNext;如果 modulePreserve,則為 Bundler;否則為 Classic

    • 允許的值
      • classic

      • node10/node

      • node16

      • nodenext

      • bundler

    • 相關選項
      • module

      • paths

      • baseUrl

      • rootDirs

      • moduleSuffixes

      • customConditions

      • resolvePackageJsonExports

      • resolvePackageJsonImports

    • 釋出版本

      1.6

    # 模組字尾 - moduleSuffixes

    提供了一種覆蓋在解析模組時搜尋的檔名字尾預設列表的方法。

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

    給定上述配置,像下面這樣的匯入

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

    TypeScript 將查詢相對檔案 ./foo.ios.ts./foo.native.ts,最後是 ./foo.ts

    注意 moduleSuffixes 中的空字串 "",這對於 TypeScript 同時查詢 ./foo.ts 是必要的。

    此功能對 React Native 專案非常有用,每個目標平臺都可以使用帶有不同 moduleSuffixes 的獨立 tsconfig.json。

    • 釋出版本

      4.7

    # 禁止解析 - noResolve

    預設情況下,TypeScript 會檢查 import<reference 指令的初始檔案集,並將這些已解析的檔案新增到您的程式中。

    如果設定了 noResolve,此過程不會發生。但是,仍會檢查 import 語句是否解析為有效模組,因此您需要確保透過其他方式滿足此要求。

    • 釋出版本

      1.0

    # 禁止未檢查的副作用匯入 - noUncheckedSideEffectImports

    在 JavaScript 中,可以在不實際匯入任何值的情況下 import 一個模組。

    ts
    import "some-module";

    這些匯入通常被稱為 副作用匯入,因為它們提供的唯一有用行為就是執行某些副作用(例如註冊全域性變數或向原型新增 polyfill)。

    預設情況下,TypeScript 不會檢查這些匯入的有效性。如果匯入解析為有效的原始檔,TypeScript 會載入並檢查該檔案。如果找不到原始檔,TypeScript 會靜默忽略該匯入。

    這是一個令人驚訝的行為,但它部分源於對 JavaScript 生態系統中模式的建模。例如,此語法也曾與打包器中的特殊載入器一起用於載入 CSS 或其他資產。您的打包器可能配置為允許透過編寫如下內容來包含特定的 .css 檔案:

    tsx
    import "./button-component.css";
    export function Button() {
    // ...
    }

    儘管如此,這掩蓋了副作用匯入中潛在的拼寫錯誤。

    當啟用 --noUncheckedSideEffectImports 時,如果找不到副作用匯入的原始檔,TypeScript 將會報錯。

    ts
    import "oops-this-module-does-not-exist";
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // error: Cannot find module 'oops-this-module-does-not-exist' or its corresponding
    // type declarations.

    啟用此選項時,一些原本有效的程式碼可能會報錯,例如上述 CSS 示例。為了解決這個問題,對於想要僅為資產編寫副作用 import 的使用者,可以透過編寫所謂的 環境模組宣告 (ambient module declaration) 和萬用字元說明符來解決。它會位於全域性檔案中,看起來如下:

    ts
    // ./src/globals.d.ts
    // Recognize all CSS files as module imports.
    declare module "*.css" {}

    事實上,您的專案中可能已經有一個這樣的檔案了!例如,執行類似 vite init 的命令可能會建立一個類似的 vite-env.d.ts

    • 預設值

      true

    • 釋出版本

      5.6

    # 路徑對映 - paths

    一系列將匯入重新對映到查詢位置的條目,這些位置相對於 baseUrl(如果已設定),否則相對於 tsconfig 檔案本身。關於 paths 的更詳細內容,請參考 moduleResolution 參考頁面

    paths 讓您可以宣告 TypeScript 應如何解析 require/import 中的匯入。

    {
    "": {
    "jquery": ["./vendor/jquery/dist/jquery"]
    }
    }
    }

    這使您能夠編寫 import "jquery",並獲得所有正確的本地型別定義。

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

    在這種情況下,您可以告知 TypeScript 檔案解析器支援許多自定義字首來查詢程式碼。

    請注意,此功能不會改變 tsc 輸出的匯入路徑,因此 paths 僅應用於通知 TypeScript 另一個工具具有此對映,並將在執行時或打包時使用它。

    • 釋出版本

      2.0

    # 解析 JSON 模組 - resolveJsonModule

    允許匯入具有 .json 副檔名的模組,這是 Node 專案中的常見做法。這包括根據靜態 JSON 結構為 import 生成型別。

    TypeScript 預設不支援解析 JSON 檔案

    ts
    // @filename: settings.json
    {
    "repo": "TypeScript",
    "dry": false,
    "debug": false
    }
    // @filename: index.ts
    import settings from "./settings.json";
    Cannot find module './settings.json' or its corresponding type declarations.2307Cannot find module './settings.json' or its corresponding type declarations.
     
    settings.debug === true;
    settings.dry === 2;
    Try

    啟用此選項後,允許匯入 JSON 並驗證該 JSON 檔案中的型別。

    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
    • 釋出版本

      2.9

    # 解析 package.json 匯出 - resolvePackageJsonExports

    --resolvePackageJsonExports 強制 TypeScript 在從 node_modules 中的包讀取時查閱 package.json 檔案的 exports 欄位

    --moduleResolution 設定為 node16nodenextbundler 時,此選項預設為 true

    • 預設值

      moduleResolutionnode16nodenextbundler 時為 true;否則為 false

    • 相關選項
      • moduleResolution

      • customConditions

      • resolvePackageJsonImports

    • 釋出版本

      5.0

    # 解析 package.json 匯入 - resolvePackageJsonImports

    --resolvePackageJsonImports 強制 TypeScript 在執行以 # 開頭的查詢時查閱 package.json 檔案的 imports 欄位,前提是執行查詢的檔案所屬的祖先目錄包含 package.json

    --moduleResolution 設定為 node16nodenextbundler 時,此選項預設為 true

    • 預設值

      moduleResolutionnode16nodenextbundler 時為 true;否則為 false

    • 相關選項
      • moduleResolution

      • customConditions

      • resolvePackageJsonExports

    • 釋出版本

      5.0

    # 重寫相對匯入副檔名 - rewriteRelativeImportExtensions

    將相對匯入路徑中的 .ts.tsx.mts.cts 副檔名重寫為輸出檔案中的 JavaScript 等效項。

    有關更多資訊,請參閱 TypeScript 5.7 釋出說明

    • 釋出版本

      5.7

    # 根目錄 - rootDir

    預設值:所有非宣告輸入檔案的最長公共路徑。如果設定了 composite,則預設值為包含 tsconfig.json 檔案的目錄。

    當 TypeScript 編譯檔案時,它會在輸出目錄中保持與輸入目錄相同的目錄結構。

    例如,假設您有一些輸入檔案:

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

    rootDir 的推斷值為所有非宣告輸入檔案的最長公共路徑,在本例中為 core/

    如果您的 outDirdist,TypeScript 將會寫入以下樹結構:

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

    然而,您可能打算讓 core 成為輸出目錄結構的一部分。透過在 tsconfig.json 中設定 rootDir: ".",TypeScript 將會寫入以下樹結構:

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

    重要的是,rootDir 不會影響哪些檔案成為編譯的一部分。它與 includeexcludefiles tsconfig.json 設定沒有互動。

    請注意,TypeScript 永遠不會將輸出檔案寫入 outDir 之外的目錄,也永遠不會跳過檔案的輸出。因此,rootDir 還會強制要求所有需要輸出的檔案都位於 rootDir 路徑之下。

    例如,假設您有這個樹結構:

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

    指定 rootDircore 同時 設定 include* 將會出錯,因為它會建立一個檔案 (helpers.ts),該檔案需要輸出到 outDir 之外 (即 ../helpers.js)。

    • 預設值

      根據輸入檔案列表計算得出。

    • 釋出版本

      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 的方式,它只是模擬了它們在執行時可以透過這些相對路徑正常工作這一假設。

    rootDirs 可用於為非 TypeScript 或 JavaScript 的檔案提供一個獨立的“型別層”,方法是為其他資料夾中生成的 .d.ts 檔案提供一個歸宿。此技術對於使用非程式碼檔案 import 的打包應用程式非常有用:

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

    這種技術讓您可以提前為非程式碼原始檔生成型別。匯入操作隨後會自然地基於原始檔的位置進行工作。例如,./src/index.ts 可以匯入檔案 ./src/css/main.css,TypeScript 將透過相應生成的宣告檔案感知該檔案型別的打包器行為。

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

      根據輸入檔案列表計算得出。

    • 釋出版本

      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

    • 相關選項
      • types

    • 釋出版本

      2.0

    # 型別包 - 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/expressnode_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
    • 不會使匯出出現在自動匯入建議中

    此功能與 typeRoots 的區別在於,它旨在僅指定您想要包含的精確型別,而 typeRoots 支援指定您想要包含的特定資料夾。

    • 相關選項
      • typeRoots

    • 釋出版本

      2.0

    #輸出 (Emit)

    # 宣告檔案 - declaration

    為專案中的每個 TypeScript 或 JavaScript 檔案生成 .d.ts 檔案。這些 .d.ts 檔案是型別定義檔案,用於描述模組的外部 API。透過 .d.ts 檔案,TypeScript 等工具可以為無型別程式碼提供智慧感知和準確的型別。

    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

    使用 JavaScript 檔案的 .d.ts 檔案時,您可能需要使用 emitDeclarationOnly 或使用 outDir 以確保 JavaScript 檔案不會被覆蓋。

    • 預設值

      如果設定了 composite 則為 true;否則為 false

    • 相關選項
      • declarationDir

      • emitDeclarationOnly

    • 釋出版本

      1.0

    # 宣告檔案目錄 - declarationDir

    提供了一種配置宣告檔案輸出根目錄的方法。

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

    使用此 tsconfig.json

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

    會將 index.ts 的 d.ts 檔案放置在 types 資料夾中

    example
    ├── index.js
    ├── index.ts
    ├── package.json
    ├── tsconfig.json
    └── types
    └── index.d.ts
    • 相關選項
      • declaration

    • 釋出版本

      2.0

    # 宣告對映 - declarationMap

    .d.ts 檔案生成源對映,將其映射回原始的 .ts 原始檔。這將允許 VS Code 等編輯器在執行 轉到定義 (Go to Definition) 等功能時跳轉到原始 .ts 檔案。

    如果您正在使用專案引用,則應強烈考慮開啟此選項。

    • 釋出版本

      2.9

    # 向下相容迭代 - downlevelIteration

    向下相容 (Downleveling) 是 TypeScript 中轉譯為舊版本 JavaScript 的術語。此標誌旨在啟用對現代 JavaScript 如何在舊版 JavaScript 執行時中迭代新概念的更準確實現的支援。

    ECMAScript 6 增加了幾個新的迭代原語:for / of 迴圈 (for (el of arr))、陣列展開 ([a, ...b])、引數展開 (fn(...args)) 和 Symbol.iteratordownlevelIteration 允許在存在 Symbol.iterator 實現的情況下,在 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 迭代協議。某些字串(例如表情符號 😜)的 .length 為 2(甚至更多!),但在 for-of 迴圈中應作為 1 個單位進行迭代。請參閱 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
    // Make a new array whose elements are 1 followed by the elements of arr2
    const arr = [1, ...arr2];

    根據描述,向下轉譯到 ES5 似乎很容易:

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

    然而,在某些罕見情況下,這是明顯不同的。

    例如,如果源陣列缺少一個或多個項(包含空洞),展開語法會將每個空項替換為 undefined,而 .concat 則會保持它們不變。

    js
    // Make an array where the element at index 1 is missing
    let arrayWithHole = ["a", , "c"];
    let spread = [...arrayWithHole];
    let concatenated = [].concat(arrayWithHole);
    console.log(arrayWithHole);
    // [ 'a', <1 empty item>, 'c' ]
    console.log(spread);
    // [ 'a', undefined, 'c' ]
    console.log(concatenated);
    // [ 'a', <1 empty item>, 'c' ]

    正如 for / of 一樣,downlevelIteration 將使用 Symbol.iterator(如果存在)來更準確地模擬 ES 6 行為。

    • 相關選項
      • importHelpers

    • 釋出版本

      2.3

    # 輸出 BOM - emitBOM

    控制 TypeScript 在編寫輸出檔案時是否輸出 位元組順序標記 (BOM)。某些執行時環境需要 BOM 才能正確解釋 JavaScript 檔案;而其他環境則要求不包含它。除非您有充分的理由更改它,否則預設值 false 通常是最好的。

    • 釋出版本

      1.0

    # 僅輸出宣告檔案 - emitDeclarationOnly

    輸出 .d.ts 檔案;不輸出 .js 檔案。

    此設定在以下兩種情況下非常有用:

    • 您正在使用 TypeScript 以外的轉譯器來生成 JavaScript。
    • 您僅使用 TypeScript 為您的消費者生成 d.ts 檔案。
    • 相關選項
      • declaration

    • 釋出版本

      2.8

    # 匯入輔助函式 - importHelpers

    對於某些降級(downleveling)操作,TypeScript 會使用一些輔助程式碼來處理諸如類擴充套件、陣列或物件展開以及非同步操作等任務。預設情況下,這些輔助函式會被插入到使用它們的檔案中。如果多個不同的模組使用相同的輔助函式,這可能會導致程式碼重複。

    如果啟用了 importHelpers 標誌,這些輔助函式將改為從 tslib 模組中匯入。你需要確保 tslib 模組能夠在執行時被匯入。此設定僅影響模組;全域性指令碼檔案不會嘗試匯入模組。

    例如,使用以下 TypeScript 程式碼

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

    啟用 downlevelIterationimportHelpers 保持為 false 時

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

    接著同時啟用 downlevelIterationimportHelpers

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

    當您提供自己的這些函式實現時,可以使用 noEmitHelpers

    • 相關選項
      • noEmitHelpers

      • downlevelIteration

    • 釋出版本

      2.1

    # 內聯原始碼對映 - inlineSourceMap

    設定後,TypeScript 不會寫入 .js.map 檔案來提供原始碼對映,而是將原始碼對映內容嵌入到 .js 檔案中。雖然這會導致 JS 檔案變大,但在某些場景下非常方便。例如,您可能希望在不允許提供 .map 檔案的 Web 伺服器上除錯 JS 檔案。

    sourceMap 互斥。

    例如,使用以下 TypeScript 程式碼

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

    轉換為此 JavaScript

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

    然後透過 inlineSourceMap 啟用構建,檔案底部會出現一個包含該檔案原始碼對映的註釋。

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

      1.5

    # 內聯原始碼 - inlineSources

    設定後,TypeScript 會將 .ts 檔案的原始內容作為嵌入字串包含在原始碼對映中(使用原始碼對映的 sourcesContent 屬性)。這通常在與 inlineSourceMap 相同的場景下非常有用。

    需要設定 sourceMapinlineSourceMap

    例如,使用以下 TypeScript 程式碼

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

    預設轉換為此 JavaScript

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

    然後透過 inlineSourcesinlineSourceMap 啟用構建,檔案底部會出現一個包含該檔案原始碼對映的註釋。請注意,結尾與 inlineSourceMap 中的示例不同,因為原始碼對映現在也包含了原始原始碼。

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

      1.5

    # 對映根路徑 - mapRoot

    指定偵錯程式查詢對映檔案的位置,而不是生成位置。此字串在原始碼對映內部按原樣處理,例如

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

    將宣告 index.js 的原始碼對映位於 https://my-website.com/debug/sourcemaps/index.js.map

    • 釋出版本

      1.0

    # 換行符 - newLine

    指定編譯檔案時使用的行尾序列:‘CRLF’ (dos) 或 ‘LF’ (unix)。

    • 預設值

      lf

    • 允許的值
      • crlf

      • lf

    • 釋出版本

      1.5

    # 不輸出 - noEmit

    不輸出編譯器生成的 JavaScript 原始碼、原始碼對映或宣告檔案。

    這為其他工具(如 Babelswc)留出了空間,由它們負責將 TypeScript 檔案轉換為可以在 JavaScript 環境中執行的檔案。

    您可以將 TypeScript 用作編輯器整合工具和原始碼型別檢查器。

    • 釋出版本

      1.5

    # 不輸出輔助函式 - noEmitHelpers

    您可以不再透過 importHelpers 匯入輔助函式,而是完全關閉輔助函式的輸出,並在全域性作用域中提供您所使用的輔助函式實現。

    例如,在 ES5 中使用此 async 函式需要 await 類函式和 generator 類函式才能執行

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

    這會建立大量的 JavaScript 程式碼

    ts
    "use strict";
    var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
    function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
    function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
    function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
    };
    var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
    if (f) throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_ = 0)), _) try {
    if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
    if (y = 0, t) op = [op[0] & 2, t.value];
    switch (op[0]) {
    case 0: case 1: t = op; break;
    case 4: _.label++; return { value: op[1], done: false };
    case 5: _.label++; y = op[1]; op = [0]; continue;
    case 7: op = _.ops.pop(); _.trys.pop(); continue;
    default:
    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
    if (t[2]) _.ops.pop();
    _.trys.pop(); continue;
    }
    op = body.call(thisArg, _);
    } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
    if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
    };
    var getAPI = function (url) { return __awaiter(void 0, void 0, void 0, function () {
    return __generator(this, function (_a) {
    // Get API
    return [2 /*return*/, {}];
    });
    }); };
     
    Try

    可以透過此標誌切換為您自己的全域性變數實現

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

    • 釋出版本

      1.5

    # 出錯時不輸出 - noEmitOnError

    如果報告了任何錯誤,則不輸出編譯器生成的 JavaScript 原始碼、原始碼對映或宣告檔案。

    此選項預設為 false,這使得在類似 watch 的開發環境中工作更容易,因為在確保所有錯誤都得到解決之前,您可能希望在另一個環境中檢視程式碼更改的結果。

    • 釋出版本

      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
    • 相關選項
      • out

      • outFile

    • 釋出版本

      1.0

    # 輸出檔案 - outFile

    如果指定,所有 全域性(非模組)檔案將被連線成指定的單個輸出檔案。

    如果 module 設定為 systemamd,所有模組檔案在所有全域性內容之後也會連線到此檔案中。

    注意:除非 moduleNoneSystemAMD,否則不能使用 outFile。此選項 不能 用於打包 CommonJS 或 ES6 模組。

    • 相關選項
      • out

      • outDir

    • 釋出版本

      1.6

    # 保留常量列舉 - preserveConstEnums

    不要在生成的程式碼中刪除 const enum 宣告。const enum 透過輸出列舉值而不是引用,提供了一種減少應用程式執行時記憶體佔用的方法。

    例如,使用以下 TypeScript

    ts
    const enum Album {
    JimmyEatWorldFutures = 1,
    TubRingZooHypothesis = 2,
    DogFashionDiscoAdultery = 3,
    }
     
    const selectedAlbum = Album.JimmyEatWorldFutures;
    if (selectedAlbum === Album.JimmyEatWorldFutures) {
    console.log("That is a great choice.");
    }
    Try

    預設的 const enum 行為是將任何 Album.Something 轉換為相應的數字字面量,並完全從 JavaScript 中刪除對列舉的引用。

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

    設定 preserveConstEnumstrue 後,enum 在執行時會保留,並且數字仍然會輸出。

    ts
    "use strict";
    var Album;
    (function (Album) {
    Album[Album["JimmyEatWorldFutures"] = 1] = "JimmyEatWorldFutures";
    Album[Album["TubRingZooHypothesis"] = 2] = "TubRingZooHypothesis";
    Album[Album["DogFashionDiscoAdultery"] = 3] = "DogFashionDiscoAdultery";
    })(Album || (Album = {}));
    const selectedAlbum = 1 /* Album.JimmyEatWorldFutures */;
    if (selectedAlbum === 1 /* Album.JimmyEatWorldFutures */) {
    console.log("That is a great choice.");
    }
     
    Try

    這實際上使此類 const enums 僅成為原始碼特性,在執行時沒有任何痕跡。

    • 預設值

      如果設定了 isolatedModules 則為 true;否則為 false

    • 釋出版本

      1.4

    # 移除註釋 - removeComments

    將 TypeScript 轉換為 JavaScript 時移除所有註釋。預設為 false

    例如,這是一個包含 JSDoc 註釋的 TypeScript 檔案

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

    removeComments 設定為 true

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

    如果不設定 removeComments 或將其設定為 false

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

    這意味著您的註釋將出現在 JavaScript 程式碼中。

    • 釋出版本

      1.0

    # 原始碼對映 - sourceMap

    啟用 原始碼對映檔案 的生成。這些檔案允許偵錯程式和其他工具在實際處理已輸出的 JavaScript 檔案時顯示原始 TypeScript 原始碼。原始碼對映檔案作為 .js.map(或 .jsx.map)檔案輸出在對應的 .js 輸出檔案旁邊。

    .js 檔案隨後將包含一個原始碼對映註釋,以向外部工具指示檔案的位置,例如

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

    設定 sourceMaptrue 進行編譯會建立以下 JavaScript 檔案

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

    並且還會生成此 json 對映

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

      1.0

    # 原始碼根路徑 - sourceRoot

    指定偵錯程式查詢 TypeScript 檔案的位置,而不是相對源位置。此字串在原始碼對映內部按原樣處理,您可以使用路徑或 URL

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

    將宣告 index.js 的原始檔位於 https://my-website.com/debug/source/index.ts

    • 釋出版本

      1.0

    # 剝離內部程式碼 - stripInternal

    不要輸出 JSDoc 註釋中帶有 @internal 註解的程式碼的宣告。這是一個內部編譯器選項;請自行承擔風險使用,因為編譯器不會檢查結果是否有效。如果您正在尋找處理 d.ts 檔案中額外可見性級別的工具,請檢視 api-extractor

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

    設定標誌為 false(預設)時

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

    stripInternal 設定為 true 時,輸出的 d.ts 將被修訂。

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

    JavaScript 輸出保持不變。

    • Internal
    • 釋出版本

      1.5

    #JavaScript 支援

    # 允許 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

    此標誌可以用作向 JS 專案中增量新增 TypeScript 檔案的方法,允許 .ts.tsx 檔案與現有 JavaScript 檔案共存。

    它還可以與 declarationemitDeclarationOnly 一起使用,以 為 JS 檔案建立宣告

    • 預設值

      false,除非設定了 checkJs

    • 相關選項
      • checkJs

      • emitDeclarationOnly

    • 釋出版本

      1.8

    # 檢查 JS - checkJs

    allowJs 配合使用。當啟用 checkJs 時,會在 JavaScript 檔案中報告錯誤。這等同於在專案中包含的所有 JavaScript 檔案頂部新增 // @ts-check

    例如,根據 TypeScript 附帶的 parseFloat 型別定義,這是不正確的 JavaScript

    js
    // parseFloat only takes a string
    module.exports.pi = parseFloat(3.142);

    當匯入到 TypeScript 模組中時

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

    您將不會得到任何錯誤。但是,如果您開啟 checkJs,則會從 JavaScript 檔案中獲得錯誤訊息。

    ts
    // @filename: constants.js
    module.exports.pi = parseFloat(3.142);
    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
    • 相關選項
      • allowJs

      • emitDeclarationOnly

    • 釋出版本

      2.3

    # 最大 Node 模組 JS 深度 - maxNodeModuleJsDepth

    node_modules 下搜尋並載入 JavaScript 檔案的最大依賴深度。

    此標誌僅在啟用 allowJs 時使用,如果您想讓 TypeScript 為 node_modules 內的所有 JavaScript 推斷型別,可以使用它。

    理想情況下,這應該保持在 0(預設值),並且應該使用 d.ts 檔案來顯式定義模組的結構。但是,在某些情況下,您可能希望以犧牲速度和潛在的準確性為代價來開啟此功能。

    • 釋出版本

      2.0

    #編輯器支援

    # 停用大小限制 - disableSizeLimit

    為了避免在使用非常大的 JavaScript 專案時出現潛在的記憶體膨脹問題,TypeScript 分配的記憶體有一個上限。開啟此標誌將移除該限制。

    • 釋出版本

      2.0

    # 外掛 - plugins

    在編輯器內執行的語言服務外掛列表。

    語言服務外掛是一種向用戶提供基於現有 TypeScript 檔案的額外資訊的方法。它們可以增強 TypeScript 和編輯器之間的現有訊息,或提供它們自己的錯誤訊息。

    例如:

    VS Code 支援擴充套件 自動包含語言服務外掛,因此您可能在編輯器中運行了一些外掛,而無需在 tsconfig.json 中定義它們。

    • 釋出版本

      2.2

    #互操作性約束

    # 允許合成預設匯入 - allowSyntheticDefaultImports

    當設定為 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";
     
    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,僅用於型別檢查。此選項使 TypeScript 的行為與 Babel 一致,其中會輸出額外的程式碼以使使用模組的預設匯出更符合人體工程學。

    # 僅可擦除語法 - erasableSyntaxOnly

    自 v23.6 起,Node.js 支援直接執行 TypeScript 檔案;但是,在這種模式下,僅支援沒有執行時語義的 TypeScript 特定語法。換句話說,必須能夠輕鬆地從檔案中 擦除 任何 TypeScript 特定語法,並留下有效的 JavaScript 檔案。

    這意味著不支援以下構造

    • enum 宣告
    • 包含執行時程式碼的 namespacemodule
    • 類中的引數屬性
    • 非 ECMAScript 的 import =export = 賦值
    • <prefix> 風格的型別斷言
    ts
    // ❌ error: An `import ... = require(...)` alias
    import foo = require("foo");
    // ❌ error: A namespace with runtime code.
    namespace container {
    foo.method();
    export type Bar = string;
    }
    // ❌ error: An `import =` alias
    import Bar = container.Bar;
    class Point {
    // ❌ error: Parameter properties
    constructor(public x: number, public y: number) {}
    }
    // ❌ error: An `export =` assignment.
    export = Point;
    // ❌ error: An enum declaration.
    enum Direction {
    Up,
    Down,
    Left,
    Right,
    }
    // ❌ error: <prefix>-style type assertion.
    const num = <number>1;

    類似 ts-blank-spaceAmaro(Node.js 中型別剝離的基礎庫)的類似工具也具有相同的限制。如果這些工具遇到不符合這些要求的程式碼,它們將提供有用的錯誤訊息,但直到您真正嘗試執行程式碼時,您才發現它無法正常工作。

    --erasableSyntaxOnly 標誌將導致 TypeScript 對大多數具有執行時行為的 TypeScript 特定構造報錯。

    ts
    class C {
    constructor(public x: number) { }
    // ~~~~~~~~~~~~~~~~
    // error! This syntax is not allowed when 'erasableSyntaxOnly' is enabled.
    }
    }

    通常,您需要將此標誌與 --verbatimModuleSyntax 結合使用,這可以確保模組包含適當的匯入語法,並且不會發生匯入省略。

      # ES 模組互操作性 - esModuleInterop

      預設情況下(esModuleInterop 為 false 或未設定),TypeScript 將 CommonJS/AMD/UMD 模組視為與 ES6 模組相似。在執行此操作時,有兩個部分被證明是錯誤的假設

      • 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 轉譯程式碼中的這兩個問題。第一個更改了編譯器中的行為,第二個透過兩個提供墊片(shim)的新輔助函式修復,以確保輸出的 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

      設定 esModuleInteroptrue

      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 () {
      var ownKeys = function(o) {
      ownKeys = Object.getOwnPropertyNames || function (o) {
      var ar = [];
      for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
      return ar;
      };
      return ownKeys(o);
      };
      return function (mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
      __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

      注意:名稱空間匯入 import * as fs from "fs" 僅考慮 自有 屬性(基本上是設定在物件上的屬性,而不是透過原型鏈設定的屬性)。如果您匯入的模組使用繼承屬性定義其 API,則需要使用預設匯入形式 (import fs from "fs"),或停用 esModuleInterop

      注意:您可以透過啟用 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

      • 推薦
      • 預設值

        如果 modulenode16nodenextpreserve 則為 true;否則為 false

      • 相關選項
        • allowSyntheticDefaultImports

      • 釋出版本

        2.7

      # 強制檔名大小寫一致 - forceConsistentCasingInFileNames

      TypeScript 遵循其執行所在檔案系統的大小寫敏感規則。如果某些開發人員在大小寫敏感的檔案系統中工作,而其他人不在,這可能會出現問題。如果一個檔案試圖透過指定 ./FileManager.ts 來匯入 fileManager.ts,該檔案在大小寫不敏感的檔案系統中可以被找到,但在大小寫敏感的檔案系統中則不行。

      當設定此選項時,如果程式嘗試以與磁碟上不同的大小寫包含檔案,TypeScript 將發出錯誤。

      • 推薦
      • 預設值

        true

      • 釋出版本

        1.8

      # 獨立宣告 - isolatedDeclarations

      要求對匯出進行足夠的標註,以便其他工具可以輕鬆生成宣告檔案。

      有關更多資訊,請參閱 5.5 版本釋出說明

      • 釋出版本

        5.5

      # 獨立模組 - isolatedModules

      雖然您可以使用 TypeScript 從 TypeScript 程式碼生成 JavaScript 程式碼,但使用其他轉譯器(如 Babel)來執行此操作也很常見。但是,其他轉譯器一次只能處理單個檔案,這意味著它們無法應用依賴於理解完整型別系統的程式碼轉換。此限制也適用於某些構建工具使用的 TypeScript 的 ts.transpileModule API。

      這些限制可能會導致某些 TypeScript 特性(如 const enumnamespace)出現執行時問題。設定 isolatedModules 標誌會告訴 TypeScript,如果您編寫了無法被單檔案轉譯過程正確解釋的特定程式碼,請向您發出警告。

      它不會改變程式碼的行為,也不會以其他方式改變 TypeScript 的檢查和輸出過程。

      啟用 isolatedModules 時無法正常工作的一些程式碼示例。

      非值識別符號的匯出

      在 TypeScript 中,您可以匯入一個 型別 然後隨後將其匯出

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

      因為沒有 someType 的值,匯出的內容將不會嘗試匯出它(這在 JavaScript 中將是一個執行時錯誤)

      js
      export { someFunction };

      單檔案轉譯器不知道 someType 是否產生一個值,因此匯出僅指代型別的名稱是一個錯誤。

      非模組檔案

      如果設定了 isolatedModules,名稱空間僅允許在 模組 中(意味著它具有某種形式的 import/export)。如果在非模組檔案中發現名稱空間,則會發生錯誤

      ts
      namespace Instantiated {
      Namespaces are not allowed in global script files when 'isolatedModules' is enabled. If this file is not intended to be a global script, set 'moduleDetection' to 'force' or add an empty 'export {}' statement.1280Namespaces are not allowed in global script files when 'isolatedModules' is enabled. If this file is not intended to be a global script, set 'moduleDetection' to 'force' or add an empty 'export {}' statement.
      export const x = 1;
      }
      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="..." /> 指令)都相對於符號連結檔案的位置進行解析,而不是相對於符號連結解析到的路徑進行解析。

      • 釋出版本

        2.5

      # 逐字模組語法 - verbatimModuleSyntax

      預設情況下,TypeScript 執行一種稱為 匯入省略(import elision) 的操作。基本上,如果您編寫如下內容

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

      TypeScript 會檢測到您僅將匯入用於型別,並完全丟棄該匯入。您的輸出 JavaScript 可能看起來像這樣

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

      大多數情況下,這很好,因為如果 Car 不是從 ./car 匯出的值,我們將得到執行時錯誤。

      但它確實為某些邊緣情況增加了一層複雜性。例如,注意沒有類似 import "./car"; 的語句 - 匯入被完全丟棄了。這對於有或沒有副作用的模組確實有影響。

      TypeScript 的 JavaScript 輸出策略還有幾層複雜性 - 匯入省略不僅由匯入的使用方式驅動 - 它通常也參考值的宣告方式。所以並不總是清楚像下面這樣的程式碼

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

      是否應該保留或丟棄。如果 Car 是用類似 class 的方式宣告的,那麼它可以在生成的 JavaScript 檔案中保留。但如果 Car 僅宣告為 type 別名或 interface,那麼 JavaScript 檔案根本不應該匯出 Car

      雖然 TypeScript 可能能夠根據跨檔案的資訊做出這些輸出決定,但並非每個編譯器都能做到。

      匯入和匯出上的 type 修飾符在一定程度上有助於解決這些情況。透過使用 type 修飾符,我們可以顯式地確定匯入或匯出是否僅用於型別分析,並可以在 JavaScript 檔案中完全丟棄。

      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 修飾符本身並不太有用 - 預設情況下,模組省略仍然會丟棄匯入,而且沒有任何東西強制您區分 type 和普通匯入/匯出。因此 TypeScript 提供了 --importsNotUsedAsValues 標誌以確保您使用 type 修飾符,--preserveValueImports 以防止 某些 模組省略行為,以及 --isolatedModules 以確保您的 TypeScript 程式碼在不同編譯器中正常工作。不幸的是,理解這 3 個標誌的細節很困難,並且仍然存在一些行為意外的邊緣情況。

      TypeScript 5.0 引入了一個名為 --verbatimModuleSyntax 的新選項來簡化這種情況。規則簡單得多 - 任何沒有 type 修飾符的匯入或匯出都會被保留。任何使用 type 修飾符的內容都會被完全丟棄。

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

      有了這個新選項,所見即所得。

      不過,這在模組互操作性方面確實有一些影響。在此標誌下,當您的設定或副檔名暗示不同的模組系統時,ECMAScript importexport 不會被重寫為 require 呼叫。相反,您會收到錯誤。如果您需要輸出使用 requiremodule.exports 的程式碼,則必須使用 ES2015 之前的 TypeScript 模組語法

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

      雖然這是一個限制,但它確實有助於使一些問題更明顯。例如,在 --module node16 下忘記設定 package.json 中的 type 欄位 是非常常見的。結果,開發人員會開始編寫 CommonJS 模組而不是 ES 模組而不自知,導致令人驚訝的查詢規則和 JavaScript 輸出。此新標誌確保您對所使用的檔案型別是有意為之,因為語法是刻意不同的。

      因為 --verbatimModuleSyntax 提供了比 --importsNotUsedAsValues--preserveValueImports 更一致的故事,所以這兩個現有的標誌已被棄用,轉而支援它。

      有關更多詳細資訊,請閱讀 原始 pull request其提案 issue

      • 釋出版本

        5.0

      #向後相容性

      # 字元集 - charset

      在舊版本的 TypeScript 中,這控制了從磁碟讀取文字檔案時使用的編碼。今天,TypeScript 預設使用 UTF-8 編碼,但會正確檢測 UTF-16 (BE 和 LE) 或 UTF-8 BOM。

      • 已棄用
      • 預設值

        utf8

      • 釋出版本

        1.0

      # 未作為值使用的匯入 - importsNotUsedAsValues

      已棄用,轉而支援 verbatimModuleSyntax

      此標誌控制 import 的工作方式,有 3 個不同的選項

      • remove: 丟棄僅引用型別的 import 語句的預設行為。

      • preserve: 保留所有值或型別從未被使用的 import 語句。這可能導致匯入/副作用被保留。

      • error: 這會保留所有匯入(與 preserve 選項相同),但當值匯入僅用作型別時會報錯。如果您想確保沒有值被意外匯入,但仍然希望明確副作用匯入,這可能很有用。

      此標誌有效,因為您可以使用 import type 顯式建立永遠不應輸出到 JavaScript 的 import 語句。

      • 預設值

        remove

      • 允許的值
        • remove

        • preserve

        • error

      • 相關選項
        • preserveValueImports

        • verbatimModuleSyntax

      • 釋出版本

        3.8

      # Keyof 僅限字串 - keyofStringsOnly

      此標誌更改 keyof 型別運算子,當應用於具有字串索引簽名的型別時,返回 string 而不是 string | number

      此標誌用於幫助人們保持 TypeScript 2.9 釋出之前 的行為。

      • 已棄用
      • 釋出版本

        2.9

      # 無隱式嚴格模式 - noImplicitUseStrict

      您不需要這個。預設情況下,在將模組檔案輸出到非 ES6 目標時,TypeScript 會在檔案頂部輸出 "use strict"; 序言。此設定停用該序言。

      • 釋出版本

        1.8

      # 無嚴格泛型檢查 - noStrictGenericChecks

      TypeScript 在比較兩個泛型函式時會統一型別引數。

      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

      此標誌可用於移除該檢查。

      • 釋出版本

        2.5

      # Out - out

      請改用 outFile

      out 選項以不可預測或不一致的方式計算最終檔案位置。此選項僅保留用於向後相容,且已棄用。

      • 已棄用
      • 相關選項
        • outDir

        • outFile

      • 釋出版本

        1.0

      # 保留值匯入 - preserveValueImports

      已棄用,轉而支援 verbatimModuleSyntax

      在某些情況下,TypeScript 無法檢測到您正在使用匯入。例如,看以下程式碼

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

      或使用“編譯為 HTML”語言(如 Svelte 或 Vue)的程式碼。preserveValueImports 將阻止 TypeScript 刪除匯入,即使它看起來未被使用。

      當與 isolatedModules 結合使用時:匯入的型別 必須 被標記為僅型別(type-only),因為一次處理單個檔案的編譯器無法知道匯入是看起來未被使用的值,還是為了避免執行時崩潰必須刪除的型別。

      • 相關選項
        • isolatedModules

        • importsNotUsedAsValues

        • verbatimModuleSyntax

      • 釋出版本

        4.5

      # 抑制多餘屬性錯誤 - suppressExcessPropertyErrors

      這將停用多餘屬性錯誤的報告,例如以下示例中所示的錯誤

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

      此標誌的新增是為了幫助人們遷移到 TypeScript 1.6 中新物件字面量的更嚴格檢查。

      我們不建議在現代程式碼庫中使用此標誌,您可以使用 // @ts-ignore 來抑制需要它的個別情況。

      • 釋出版本

        1.6

      # 抑制隱式 Any 索引錯誤 - suppressImplicitAnyIndexErrors

      開啟 suppressImplicitAnyIndexErrors 會抑制在索引物件時關於隱式 anys 的錯誤報告,如以下示例所示

      ts
      const obj = { x: 10 };
      console.log(obj["foo"]);
      Element implicitly has an 'any' type because expression of type '"foo"' can't be used to index type '{ x: number; }'. Property 'foo' does not exist on type '{ x: number; }'.7053Element implicitly has an 'any' type because expression of type '"foo"' can't be used to index type '{ x: number; }'. Property 'foo' does not exist on type '{ x: number; }'.
      Try

      使用 suppressImplicitAnyIndexErrors 是一種非常激進的方法。建議改用 @ts-ignore 註釋

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

      • 釋出版本

        1.4

      #語言和環境

      # 輸出裝飾器元資料 - emitDecoratorMetadata

      啟用對為裝飾器輸出型別元資料的實驗性支援,這適用於 reflect-metadata 模組。

      例如,這是 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

      當未設定 emitDecoratorMetadata 為 true(預設)時,輸出的 JavaScript 是

      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

      當設定 emitDecoratorMetadata 為 true 時,輸出的 JavaScript 是

      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
      • 相關選項
        • experimentalDecorators

      • 釋出版本

        1.5

      # 實驗性裝飾器 - experimentalDecorators

      啟用 對裝飾器的實驗性支援,這是早於 TC39 標準化過程的裝飾器版本。

      裝飾器是一種尚未完全批准進入 JavaScript 規範的語言特性。這意味著 TypeScript 中的實現版本在 TC39 決定 JavaScript 實現時可能會有所不同。

      您可以在 手冊 中瞭解更多關於 TypeScript 中裝飾器支援的資訊。

      • 相關選項
        • emitDecoratorMetadata

      • 釋出版本

        1.5

      # JSX - jsx

      控制 JSX 構造在 JavaScript 檔案中的輸出方式。這僅影響以 .tsx 檔案開頭並生成的 JS 檔案的輸出。

      • react-jsx: 輸出 JSX 更改為針對生產環境最佳化的 _jsx 呼叫的 .js 檔案
      • react-jsxdev: 輸出 JSX 更改為僅用於開發的 _jsx 呼叫的 .js 檔案
      • preserve: 輸出 JSX 未更改的 .jsx 檔案
      • react-native: 輸出 JSX 未更改的 .js 檔案
      • react: 輸出 JSX 更改為等效的 React.createElement 呼叫的 .js 檔案

      例如

      此示例程式碼

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

      React: "react-jsx"[1]

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

      React 開發轉換: "react-jsxdev"[1]

      tsx
      import { jsxDEV as _jsxDEV } from "react/jsx-dev-runtime";
      const _jsxFileName = "/home/runner/work/TypeScript-Website/TypeScript-Website/packages/typescriptlang-org/index.tsx";
      export const HelloWorld = () => _jsxDEV("h1", { children: "Hello world" }, void 0, false, { fileName: _jsxFileName, lineNumber: 9, columnNumber: 33 }, this);
       
      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 執行時: "react"

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

      此選項也可以在每個檔案基礎上使用 @jsxRuntime 註釋使用。

      始終為此檔案使用經典執行時 ("react")

      tsx
      /* @jsxRuntime classic */
      export const HelloWorld = () => <h1>Hello world</h1>;

      始終為此檔案使用自動執行時 ("react-jsx")

      tsx
      /* @jsxRuntime automatic */
      export const HelloWorld = () => <h1>Hello world</h1>;
      • 允許的值
        • preserve

        • react

        • react-native

        • react-jsx

        • react-jsxdev

      • 相關選項
        • jsxFactory

        • jsxFragmentFactory

        • jsxImportSource

      • 釋出版本

        1.6

      # JSX 工廠 - jsxFactory

      更改在使用經典 JSX 執行時編譯 JSX 元素時在 .js 檔案中呼叫的函式。最常見的更改是如果使用 preact,則使用 "h""preact.h" 而不是預設的 "React.createElement"

      例如,此 TSX 檔案

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

      使用 jsxFactory: "h" 看起來像

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

      此選項也可以在每個檔案基礎上使用,類似於 Babel 的 /** @jsx h */ 指令

      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

      所選的工廠還將影響 JSX 名稱空間的查詢位置(用於型別檢查資訊),然後再回退到全域性名稱空間。

      如果工廠定義為 React.createElement(預設值),編譯器將在檢查全域性 JSX 之前檢查 React.JSX。如果工廠定義為 h,它將在全域性 JSX 之前檢查 h.JSX

      • 預設值

        React.createElement

      • 允許的值
        • 任何識別符號或點分隔識別符號。

      • 相關選項
        • jsx

        • jsxFragmentFactory

        • jsxImportSource

      • 釋出版本

        2.2

      # JSX 片段工廠 - jsxFragmentFactory

      指定在以 jsxFactory 編譯器選項指定的目標 React JSX 輸出時使用的 JSX 片段工廠函式,例如 Fragment

      例如,使用此 TSConfig

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

      此 TSX 檔案

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

      看起來會像

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

      此選項也可以在每個檔案基礎上使用,類似於 Babel 的 /* @jsxFrag h */ 指令

      例如:

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

        React.Fragment

      • 相關選項
        • jsx

        • jsxFactory

        • jsxImportSource

      • 釋出版本

        4.0

      # JSX 匯入源 - jsxImportSource

      宣告在使用 TypeScript 4.1 中引入的 "react-jsx""react-jsxdev" 作為 jsx 時,用於匯入 jsxjsxs 工廠函式的模組說明符。

      藉助 React 17,該庫透過單獨的匯入支援一種新形式的 JSX 轉換。

      例如,使用此程式碼

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

      使用此 TSConfig

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

      TypeScript 輸出的 JavaScript 是

      tsx
      "use strict";
      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

      例如,如果您想使用 "jsxImportSource": "preact",您需要一個像這樣的 tsconfig

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

      它會生成像這樣的程式碼

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

      或者,您可以使用每個檔案的 pragma 來設定此選項,例如

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

      將新增 preact/jsx-runtime 作為 _jsx 工廠的匯入。

      注意: 為了讓它按照您的預期工作,您的 tsx 檔案必須包含 exportimport,以便它被視為一個模組。

      • 預設值

        react

      • 相關選項
        • jsx

        • jsxFactory

      • 釋出版本

        4.1

      # 庫 - lib

      TypeScript 包含一組內建 JS API(如 Math)的預設型別定義,以及在瀏覽器環境(如 document)中找到的內容的型別定義。TypeScript 還包括與您指定的 target 匹配的較新 JS 特性的 API;例如,如果 targetES6 或更高版本,則 Map 的定義是可用的。

      由於以下幾個原因,您可能需要更改這些設定

      • 您的程式不在瀏覽器中執行,因此您不需要 "dom" 型別定義
      • 您的執行時平臺提供某些 JavaScript API 物件(可能是透過 polyfills),但尚不支援給定 ECMAScript 版本的完整語法
      • 您擁有高階 ECMAScript 版本中部分(但不是全部)功能的 polyfills 或原生實現

      在 TypeScript 4.5 中,lib 檔案可以被 npm 模組覆蓋,請在 部落格 中瞭解更多資訊。

      高階庫

      名稱 內容
      ES5 所有 ES5 功能的核心定義
      ES2015 ES2015(也稱為 ES6)中可用的額外 API - array.find, Promise, Proxy, Symbol, Map, Set, Reflect 等。
      ES6 “ES2015” 的別名
      ES2016 ES2016 中可用的額外 API - array.include 等。
      ES7 “ES2016” 的別名
      ES2017 ES2017 中可用的額外 API - Object.entries, Object.values, Atomics, SharedArrayBuffer, date.formatToParts, 型別化陣列等。
      ES2018 ES2018 中可用的額外 API - async 可迭代物件, promise.finally, Intl.PluralRules, regexp.groups 等。
      ES2019 ES2019 中可用的額外 API - array.flat, array.flatMap, Object.fromEntries, string.trimStart, string.trimEnd 等。
      ES2020 ES2020 中可用的額外 API - string.matchAll 等。
      ES2021 ES2021 中可用的額外 API - promise.any, string.replaceAll 等。
      ES2022 ES2022 中可用的額外 API - array.at, RegExp.hasIndices 等。
      ES2023 ES2023 中可用的額外 API - array.with, array.findLast, array.findLastIndex, array.toSorted, array.toReversed 等。
      ESNext ESNext 中可用的額外 API - 這會隨著 JavaScript 規範的發展而變化
      DOM DOM 定義 - window, document 等。
      WebWorker WebWorker 上下文中可用的 API
      ScriptHost Windows 指令碼宿主系統 的 API

      單獨的庫元件

      名稱
      DOM.Iterable
      ES2015.Core
      ES2015.Collection
      ES2015.Generator
      ES2015.Iterable
      ES2015.Promise
      ES2015.Proxy
      ES2015.Reflect
      ES2015.Symbol
      ES2015.Symbol.WellKnown
      ES2016.Array.Include
      ES2017.object
      ES2017.Intl
      ES2017.SharedMemory
      ES2017.String
      ES2017.TypedArrays
      ES2018.Intl
      ES2018.Promise
      ES2018.RegExp
      ES2019.Array
      ES2019.Object
      ES2019.String
      ES2019.Symbol
      ES2020.String
      ES2020.Symbol.wellknown
      ES2021.Promise
      ES2021.String
      ES2021.WeakRef
      ESNext.AsyncIterable
      ESNext.Array
      ESNext.Intl
      ESNext.Symbol

      此列表可能已過時,您可以在 TypeScript 原始碼 中檢視完整列表。

      • 相關選項
        • noLib

      • 釋出版本

        2.0

      # 庫替換 - libReplacement

      TypeScript 4.5 引入了用自定義檔案替換預設 lib 檔案的可能性。所有內建庫檔案首先會嘗試從名為 @typescript/lib-* 的包中解析。例如,您可以使用以下 package.json 將您的 dom 庫鎖定到 @types/web 的特定版本

      json
      {
      "devDependencies": {
      "@typescript/lib-dom": "npm:@types/web@0.0.199"
      }
      }

      安裝後,應該存在一個名為 @typescript/lib-dom 的包,TypeScript 在搜尋 lib.dom.d.ts 時將始終在那裡查詢。

      --libReplacement 標誌允許您停用此行為。如果您不使用任何 @typescript/lib-* 包,您現在可以使用 --libReplacement false 停用這些包查詢。將來,--libReplacement false 可能成為預設設定,因此如果您當前依賴此行為,則應考慮使用 --libReplacement true 顯式啟用它。

        # 模組檢測 - moduleDetection

        此設定控制 TypeScript 如何確定檔案是 指令碼還是模組

        有三種選擇

        • "auto"(預設) - TypeScript 不僅會查詢 import 和 export 語句,在執行 module: nodenextnode16 時,還會檢查 package.json 中的 "type" 欄位是否設定為 "module",並在執行 jsx: react-jsx 時檢查當前檔案是否為 JSX 檔案。

        • "legacy" - 與 4.6 及更早版本相同的行為,使用 import 和 export 語句來確定檔案是否為模組。

        • "force" - 確保每個非宣告檔案都被視為模組。

        • 預設值

          "auto": 將帶有 import、export、import.meta、jsx(帶有 jsx: react-jsx)或 esm 格式(帶有 module: node16+)的檔案視為模組。

        • 允許的值
          • legacy

          • auto

          • force

        • 釋出版本

          4.7

        # 無庫 - noLib

        停用任何庫檔案的自動包含。如果設定了此選項,則忽略 lib

        如果沒有一組用於關鍵原語的介面(如:Array, Boolean, Function, IArguments, Number, Object, RegExpString),TypeScript 無法 編譯任何內容。預計如果您使用 noLib,您將包含自己的這些型別定義。

        • 相關選項
          • lib

        • 釋出版本

          1.0

        # React 名稱空間 - reactNamespace

        請改用 jsxFactory。當為 TSX 檔案將目標設為 react 時,指定為 createElement 呼叫的物件。

        • 預設值

          React

        • 釋出版本

          1.8

        # 目標 - target

        現代瀏覽器支援所有 ES6 功能,因此 ES6 是一個不錯的選擇。如果您的程式碼部署到較舊的環境,您可以選擇設定更低的目標;如果保證您的程式碼在較新的環境中執行,則可以選擇更高的目標。

        target 設定更改了哪些 JS 功能被降級以及哪些功能被保持原樣。例如,如果 target 為 ES5 或更低,箭頭函式 () => this 將被轉換為等效的 function 表示式。

        更改 target 也會更改 lib 的預設值。您可以根據需要“混合和匹配” targetlib 設定,但為了方便起見,您可以直接設定 target

        對於像 Node 這樣的開發者平臺,根據平臺的型別及其版本,有 target 的基準。您可以在 tsconfig/bases 找到社群組織的 TSConfig 集,其中包含針對常見平臺及其版本的配置。

        特殊的 ESNext 值指代您的 TypeScript 版本支援的最高版本。此設定應謹慎使用,因為它在不同的 TypeScript 版本之間並不代表相同的意思,並且會使升級變得不太可預測。

        • 預設值

          如果 modulenode20 則為 es2023;如果 modulenodenext 則為 esnext;否則為 ES5

        • 允許的值
          • es3

          • es5

          • es6/es2015

          • es2016

          • es2017

          • es2018

          • es2019

          • es2020

          • es2021

          • es2022

          • es2023

          • es2024

          • es2025

          • esnext

        • 釋出版本

          1.0

        # 類欄位使用 Define - useDefineForClassFields

        此標誌用作遷移到即將到來的標準版類欄位的一部分。TypeScript 在 TC39 批准類欄位之前多年就引入了它們。即將到來的規範的最新版本具有與 TypeScript 實現不同的執行時行為,但語法相同。

        此標誌切換到即將到來的 ECMA 執行時行為。

        您可以閱讀 3.7 版本釋出說明 中關於過渡的更多資訊。

        • 預設值

          如果 targetES2022 或更高版本(包括 ESNext)則為 true;否則為 false

        • 釋出版本

          3.7

        #編譯器診斷

        # 診斷 - diagnostics

        用於輸出用於除錯的診斷資訊。此命令是 extendedDiagnostics 的子集,後者是更面向使用者的結果,更容易解釋。

        如果您被 TypeScript 編譯器工程師要求在編譯中使用此標誌給出結果,使用 extendedDiagnostics 也完全沒問題。

        • 已棄用
        • 相關選項
          • extendedDiagnostics

        • 釋出版本

          1.0

        # 解釋檔案 - explainFiles

        列印 TypeScript 視為您專案一部分的檔名稱以及它們成為編譯一部分的原因。

        例如,對於這個僅包含單個 index.ts 檔案的專案

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

        使用將 explainFiles 設定為 true 的 tsconfig.json

        json
        {
        "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "explainFiles": true
        }
        }

        針對此資料夾執行 TypeScript 的輸出如下

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

        上面的輸出顯示

        • 基於 target 的初始 lib.d.ts 查詢,以及所引用的 .d.ts 檔案鏈
        • 透過 include 預設模式定位的 index.ts 檔案

        此選項旨在用於除錯檔案如何成為您編譯的一部分。

        • 釋出版本

          4.2

        # 擴充套件診斷 - extendedDiagnostics

        您可以使用此標誌來發現 TypeScript 在編譯時花費時間的地方。這是一種用於理解您的程式碼庫整體效能特徵的工具。

        您可以瞭解更多關於如何衡量和理解效能 Wiki 部分 中的輸出的資訊。

        • 相關選項
          • diagnostics

        • 釋出版本

          2.0

        # 生成 CPU 配置 - generateCpuProfile

        此選項使您有機會在編譯器執行時讓 TypeScript 生成 v8 CPU 配置檔案。CPU 配置檔案可以幫助您瞭解構建緩慢的原因。

        此選項只能透過 CLI 使用:--generateCpuProfile tsc-output.cpuprofile

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

        該檔案可以在基於 Chromium 的瀏覽器(如 Chrome 或 Edge Developer)中的 CPU 分析器部分開啟。您可以在 TypeScript Wiki 關於效能的部分中瞭解更多關於如何理解編譯器效能的資訊。

        • 預設值

          profile.cpuprofile

        • 釋出版本

          3.7

        # generateTrace - generateTrace

        生成事件跟蹤和型別列表。
        • 釋出版本

          4.1

        # 列出已生成檔案 - listEmittedFiles

        將編譯過程中生成的檔案的名稱列印到終端。

        此標誌在以下兩種情況下非常有用:

        • 當您希望在終端的構建鏈中轉譯 TypeScript,且檔名需要在下一個命令中處理時。
        • 當您不確定 TypeScript 是否包含了您預期的檔案,作為除錯檔案包含設定的一部分時。

        例如:

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

        使用

        {
        "": true,
        }
        }

        會輸出路徑,例如

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

        通常,TypeScript 在成功時會保持靜默。

        • 釋出版本

          2.0

        # 列出檔案 - listFiles

        列印編譯過程中包含的檔名。當您不確定 TypeScript 是否包含了您預期的檔案時,這非常有用。

        例如:

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

        使用

        {
        "": true
        }
        }

        會輸出路徑,例如

        $ npm run tsc
        path/to/example/node_modules/typescript/lib/lib.d.ts
        path/to/example/node_modules/typescript/lib/lib.es5.d.ts
        path/to/example/node_modules/typescript/lib/lib.dom.d.ts
        path/to/example/node_modules/typescript/lib/lib.webworker.importscripts.d.ts
        path/to/example/node_modules/typescript/lib/lib.scripthost.d.ts
        path/to/example/index.ts

        注意,如果您使用的是 TypeScript 4.2,建議使用 explainFiles,它還會提供檔案被新增原因的解釋。

        • 相關選項
          • explainFiles

        • 釋出版本

          1.5

        # noCheck - noCheck

        停用全面型別檢查(僅報告關鍵的解析和生成錯誤)。
        • 釋出版本

          5.6

        # 跟蹤解析 - traceResolution

        當您試圖除錯為什麼某個模組未被包含時,可以將 traceResolution 設定為 true,讓 TypeScript 列印每個已處理檔案的解析過程資訊。

        • 釋出版本

          2.0

        #專案 (Projects)

        # 複合專案 - composite

        composite 選項強制執行某些約束,使構建工具(包括 TypeScript 本身,在 --build 模式下)能夠快速確定專案是否已構建。

        開啟此設定時:

        • rootDir 設定(如果未顯式設定)預設為包含 tsconfig.json 檔案的目錄。

        • 所有實現檔案必須與 include 模式匹配,或列在 files 陣列中。如果違反此約束,tsc 將告知您哪些檔案未被指定。

        • declaration 預設為 true

        您可以在手冊中找到有關 TypeScript 專案的文件。

        • 相關選項
          • incremental

          • tsBuildInfoFile

        • 釋出版本

          3.0

        # 停用引用專案載入 - disableReferencedProjectLoad

        在多專案 TypeScript 程式中,TypeScript 會將所有可用專案載入到記憶體中,以便為需要完整知識圖譜的編輯器響應(如“查詢所有引用”)提供準確結果。

        如果您的專案很大,可以使用 disableReferencedProjectLoad 標誌來停用所有專案的自動載入。相反,專案會隨著您在編輯器中開啟檔案而動態載入。

        • 釋出版本

          4.0

        # 停用解決方案搜尋 - disableSolutionSearching

        在使用 複合 TypeScript 專案 時,此選項提供了一種宣告方式,表示您不希望在編輯器中使用“查詢所有引用”或“跳轉到定義”等功能時包含該專案。

        此標誌可用於提高大型複合專案的響應速度。

        • 釋出版本

          3.8

        # 停用源專案引用重定向 - disableSourceOfProjectReferenceRedirect

        在使用 複合 TypeScript 專案 時,此選項提供了一種方式,可以回到 3.7 版本之前的行為,即使用 d.ts 檔案作為模組之間的邊界。在 3.7 版本中,真相來源現在是您的 TypeScript 檔案。

        • 釋出版本

          3.7

        # 增量構建 - incremental

        告訴 TypeScript 將上一次編譯的專案圖資訊儲存到磁碟上的檔案中。這會在您的編譯輸出資料夾中建立一系列 .tsbuildinfo 檔案。它們不會在 JavaScript 執行時被使用,可以安全刪除。您可以在 3.4 版本說明中閱讀有關此標誌的更多資訊。

        要控制檔案構建到的資料夾,請使用配置選項 tsBuildInfoFile

        • 預設值

          如果設定了 composite 則為 true;否則為 false

        • 相關選項
          • composite

          • tsBuildInfoFile

        • 釋出版本

          3.4

        # TS 構建資訊檔案 - tsBuildInfoFile

        此設定允許您指定一個檔案,用於儲存複合專案的一部分增量編譯資訊,從而加快大型 TypeScript 程式碼庫的構建速度。您可以在 手冊中閱讀有關複合專案的更多資訊。

        預設值取決於其他設定的組合:

        • 如果設定了 outFile,預設值為 <outFile>.tsbuildinfo
        • 如果設定了 rootDiroutDir,則檔案為 <outDir>/<相對於 rootDir 的 config 路徑>/<配置名>.tsbuildinfo。例如,如果 rootDirsrcoutDirdest,且配置為 ./tsconfig.json,則預設值為 ./tsconfig.tsbuildinfo,因為從 src/./tsconfig.json 的相對路徑是 ../
        • 如果設定了 outDir,則預設值為 <outDir>/<配置名>.tsbuildInfo
        • 否則,預設值為 <配置名>.tsbuildInfo
        • 預設值

          .tsbuildinfo

        • 相關選項
          • incremental

          • composite

        • 釋出版本

          3.4

        #輸出格式 (Output Formatting)

        # 不截斷錯誤 - noErrorTruncation

        不截斷錯誤訊息。

        預設情況下為 false

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

        設定為 true

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

          1.0

        # 保留監視輸出 - preserveWatchOutput

        在監視模式下,是否保留過時的控制檯輸出,而不是每次發生更改時都清屏。

        • Internal
        • 釋出版本

          2.8

        # 漂亮輸出 - pretty

        使用顏色和上下文風格化錯誤和訊息。此選項預設開啟,旨在讓編譯器輸出的訊息不那麼簡練、單調。

        • 預設值

          true

        • 釋出版本

          1.8

        #完整性 (Completeness)

        # 跳過預設庫檢查 - skipDefaultLibCheck

        改用 skipLibCheck。跳過預設庫宣告檔案的型別檢查。

        • 釋出版本

          1.6

        # 跳過庫檢查 - skipLibCheck

        跳過宣告檔案的型別檢查。

        這可以節省編譯時間,但會犧牲型別系統的準確性。例如,兩個庫可能會以不一致的方式定義同一個 type 的兩個副本。TypeScript 不會對所有 d.ts 檔案進行全面檢查,而是僅對您在應用程式原始碼中明確引用的程式碼進行型別檢查。

        一個常見的場景是,當您的 node_modules 中存在庫型別的兩個副本時,您可能會想使用 skipLibCheck。在這些情況下,您應該考慮使用像 Yarn 的 resolutions 這樣的功能,以確保樹中只有一個依賴副本,或者通過了解依賴項解析過程來找出確保只有一個副本的方法,從而在不增加額外工具的情況下解決問題。

        另一種可能性是當您在 TypeScript 釋出版本之間遷移,且這些變更導致了 node_modules 和 JS 標準庫中的中斷,而您不想在 TypeScript 更新期間處理這些問題。

        注意,如果這些問題來自 TypeScript 標準庫,您可以使用 TypeScript 4.5 的庫替換技術來替換該庫。

        • 推薦
        • 釋出版本

          2.0

        #命令列選項 (Command Line)

        #監視選項 (Watch Options)

        TypeScript 3.8 推出了一種監視目錄的新策略,這對於高效捕獲 node_modules 的更改至關重要。

        在 Linux 等作業系統上,TypeScript 會在 node_modules 及其許多子目錄上安裝目錄監視器(而不是檔案監視器)來檢測依賴項更改。這是因為可用檔案監視器的數量通常遠小於 node_modules 中的檔案數量,而需要跟蹤的目錄要少得多。

        由於每個專案可能在不同的策略下工作得更好,並且這種新方法可能不適合您的工作流程,TypeScript 3.8 引入了一個新的 watchOptions 欄位,允許使用者告知編譯器/語言服務應使用哪些監視策略來跟蹤檔案和目錄。

        # 假設更改僅影響直接依賴項 - assumeChangesOnlyAffectDirectDependencies

        啟用此選項後,TypeScript 將避免重新檢查/重新構建所有真正可能受影響的檔案,而僅重新檢查/重新構建已更改的檔案以及直接匯入它們的檔案。

        這可以被認為是監視演算法的一種“快速且寬鬆”的實現,它可以在偶爾需要執行完整構建以獲取所有編譯器錯誤訊息的前提下,顯著減少增量重新構建的時間。

        • 釋出版本

          3.8

        監視選項

        您可以配置 TypeScript --watch 的工作方式。此部分主要用於處理 fs.watchfs.watchFile 具有額外限制的情況(如在 Linux 上)。您可以在配置監視中閱讀更多資訊。

        # 監視檔案 - watchFile

        監視單個檔案的策略。

        • fixedPollingInterval:以固定的間隔每秒檢查每個檔案是否有更改多次。
        • priorityPollingInterval:每秒檢查每個檔案多次,但使用啟發式方法,某些型別的檔案檢查頻率比其他檔案低。
        • dynamicPriorityPolling:使用動態佇列,修改頻率較低的檔案檢查頻率較低。
        • useFsEvents(預設值):嘗試使用作業系統/檔案系統的原生事件來監控檔案更改。
        • useFsEventsOnParentDirectory:嘗試使用作業系統/檔案系統的原生事件來監聽檔案父目錄的更改。
        • 允許的值
          • fixedpollinginterval

          • prioritypollinginterval

          • dynamicprioritypolling

          • fixedchunksizepolling

          • usefsevents

          • usefseventsonparentdirectory

        • 釋出版本

          3.8

        # 監視目錄 - watchDirectory

        在缺乏遞迴檔案監視功能的系統下,監視整個目錄樹的策略。

        • fixedPollingInterval:以固定間隔每秒檢查每個目錄是否有更改多次。
        • dynamicPriorityPolling:使用動態佇列,修改頻率較低的目錄檢查頻率較低。
        • useFsEvents(預設值):嘗試使用作業系統/檔案系統的原生事件來監視目錄更改。
        • 允許的值
          • usefsevents

          • fixedpollinginterval

          • dynamicprioritypolling

          • fixedchunksizepolling

        • 釋出版本

          3.8

        # 後備輪詢 - fallbackPolling

        使用檔案系統事件時,此選項指定當系統耗盡原生檔案監視器和/或不支援原生檔案監視器時使用的輪詢策略。

        • fixedPollingInterval:以固定的間隔每秒檢查每個檔案是否有更改多次。
        • priorityPollingInterval:每秒檢查每個檔案多次,但使用啟發式方法,某些型別的檔案檢查頻率比其他檔案低。
        • dynamicPriorityPolling:使用動態佇列,修改頻率較低的檔案檢查頻率較低。
        • synchronousWatchDirectory:停用目錄的延遲監視。延遲監視在大量檔案更改同時發生時非常有用(例如,執行 npm installnode_modules 中的更改),但在某些不常見的設定中,您可能希望透過此標誌停用它。
        • 允許的值
          • fixedinterval

          • priorityinterval

          • dynamicpriority

          • fixedchunksize

        • 釋出版本

          3.8

        # 同步監視目錄 - synchronousWatchDirectory

        在原生不支援遞迴監視的平臺上,同步呼叫回撥並更新目錄監視器的狀態。而不是給予一個小的超時時間來允許檔案上可能發生多次編輯。

        {
        "watchOptions": {
        }
        }
        • 釋出版本

          3.8

        # 排除目錄 - excludeDirectories

        您可以使用 excludeFiles 來大幅減少在 --watch 期間監視的檔案數量。這對於減少 Linux 上 TypeScript 跟蹤的開啟檔案數量非常有用。

        {
        "watchOptions": {
        "": ["**/node_modules", "_build", "temp/*"]
        }
        }
        • 釋出版本

          4.2

        # 排除檔案 - excludeFiles

        您可以使用 excludeFiles 從監視的檔案集合中移除一組特定的檔案。

        {
        "watchOptions": {
        "": ["temp/file.ts"]
        }
        }
        • 釋出版本

          4.2

        型別獲取 (Type Acquisition)

        型別獲取僅對 JavaScript 專案重要。在 TypeScript 專案中,您需要顯式包含專案中的型別。然而,對於 JavaScript 專案,TypeScript 工具會在後臺自動為您下載模組的型別,並將其放置在您的 node_modules 資料夾之外。

        # 啟用 - enable

        停用 JavaScript 專案中的自動型別獲取。

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

          # 包含 - include

          如果您有一個 JavaScript 專案,需要額外的指導來讓 TypeScript 理解全域性依賴項,或者透過 disableFilenameBasedTypeAcquisition 停用了內建推理。

          您可以使用 include 指定應從 DefinitelyTyped 使用哪些型別。

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

          # 排除 - exclude

          提供一個配置,用於停用 JavaScript 專案中特定模組的型別獲取。這對於那些在測試基礎設施中包含其他庫,但這些庫在主應用程式中並不需要的專案非常有用。

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

          # 停用基於檔名的型別獲取 - disableFilenameBasedTypeAcquisition

          TypeScript 的型別獲取可以根據專案中的檔名推斷應該新增哪些型別。這意味著專案中存在 jquery.js 這樣的檔案時,會自動從 DefinitelyTyped 下載 jQuery 的型別。

          您可以透過 disableFilenameBasedTypeAcquisition 停用此功能。

          json
          {
          "typeAcquisition": {
          "disableFilenameBasedTypeAcquisition": true
          }
          }
          • 釋出版本

            4.1