Compiler Options

"compilerOptions"

JavaScript Support
  1. allowJs,
  2. checkJs and
  3. maxNodeModuleJsDepth
Editor Support
  1. disableSizeLimit and
  2. plugins
Baris Perintah

    Root Fields

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

    # Files - files

    Menentukan daftar berkas yang diijinkan untuk disertakan dalam program. Kesalahan terjadi jika salah satu berkas tidak dapat ditemukan.

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

    Ini berguna ketika Anda hanya memiliki sejumlah berkas kecil dan tidak perlu menggunakan glob untuk mereferensikan banyak berkas. Jika Anda membutuhkannya, gunakan include.

    # Extends - extends

    Nilai extends adalah string yang berisi jalur ke berkas konfigurasi lain untuk mewarisi. Jalur tersebut mungkin menggunakan resolusi gaya Node.js.

    Konfigurasi dari berkas dasar dimuat terlebih dahulu, kemudian diganti dengan yang ada di berkas konfigurasi pewarisan. Semua jalur relatif yang ditemukan di berkas konfigurasi akan diselesaikan secara relatif terhadap berkas konfigurasi tempat asalnya.

    Perlu diperhatikan bahwa files,include dan exclude dari berkas konfigurasi pewaris menimpa konfigurasi yang berasal dari berkas konfigurasi asal, dan sirkularitas antara berkas konfigurasi tidak diperbolehkan.

    Saat ini, satu-satunya properti tingkat atas yang dikecualikan dari pewarisan adalah referensi.

    Contoh

    configs/base.json:

    tsconfig.json:

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

    tsconfig.nostrictnull.json:

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

    Properti dengan jalur relatif yang ditemukan di berkas konfigurasi, yang tidak dikecualikan dari pewarisan, akan diresolusikan secara relatif terhadap berkas konfigurasi tempat asalnya.

    • Default:

      false

    • Released:

      2.1

    # Disertakan (_Include_) - include

    Menentukan sebuah susunan nama berkas atau contoh berkas untuk dimasukkan ke dalam program. Nama berkas ini diselesaikan dengan direktori yang berisi berkas tsconfig.json.

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

    Yang akan mencakup:

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

    include dan exclude mendukung karakter untuk membuat pola global:

    • * cocok dengan nol atau lebih karakter (tidak termasuk pemisah direktori)
    • ? cocok dengan salah satu karakter (tidak termasuk pemisah direktori)
    • **/ cocok dengan direktori apa pun yang bertingkat.

    Jika contoh umum tidak menyertakan ekstensi berkas, maka hanya berkas dengan ekstensi yang didukung yang disertakan (misalnya .ts,.tsx, dan .d.ts secara default, dengan.js dan . jsx jika allowJs disetel ke true).

    # Exclude - exclude

    Menentukan array nama berkas atau pola yang harus dilewati saat menyelesaikan include.

    Penting: exclude hanya mengubah berkas mana yang disertakan sebagai hasil dari pengaturan include. Berkas yang ditentukan oleh exclude masih bisa menjadi bagian dari basis kode Anda karena pernyataan import dalam kode Anda, penyertaan types, perintah /// <reference, atau ditentukan dalam daftar files.

    Ini bukan mekanisme yang mencegah berkas untuk disertakan dalam basis kode - ini hanya mengubah apa yang ditemukan oleh setelan include.

    # Referensi - references

    Referensi proyek adalah cara untuk menyusun program TypeScript Anda menjadi bagian-bagian yang lebih kecil. Menggunakan Referensi Proyek dapat sangat meningkatkan waktu interaksi build dan editor, menerapkan pemisahan logika antar komponen, dan mengatur kode Anda dengan cara yang baru dan lebih baik.

    Anda dapat membaca lebih lanjut tentang bagaimana cara kerja referensi di bagian Referensi Proyek dari buku pegangan

    • Default:

      false

    Pilihan - Pilihan Kompiler

    Banyak pilihan yang membuat jumlah besar di pengaturan Typescript’s dan itu juga meliputi bagaimana bahasa seharusnya bekerja.

    #Type Checking

    # Izinkan Kode Tak Terjangkau - allowUnreachableCode

    Kapan:

    • undefined default memberikan saran sebagai peringatan kepada editor
    • true kode yang tidak dapat dijangkau diabaikan
    • false menimbulkan galat kompiler tentang kode yang tidak dapat dijangkau

    Peringatan ini hanya tentang kode yang terbukti tidak dapat dijangkau karena penggunaan sintaks JavaScript, misalnya:

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

    Dengan "allowUnreachableCode": false:

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

    Ini tidak mempengaruhi galat atas dasar kode yang muncul menjadi tidak dapat dijangkau karena menggolongkan uraian.

    # Izinkan Label yang Tidak Digunakan - allowUnusedLabels

    Setel ke false untuk menonaktifkan peringatan tentang label yang tidak digunakan.

    Label sangat jarang di JavaScript dan biasanya menunjukkan upaya untuk menulis objek dengan tepat:

    ts
    function verifikasiUmur(umur: number) {
    // Lupa menulis pernyataan 'return'
    if (umur > 18) {
    terverifikasi: true;
    Unused label.7028Unused label.
    }
    }
    Try

    # Selalu Tepat - alwaysStrict

    Pastikan bahwa berkas Anda diurai di Mode strict EcmaScript, dan mengeluarkan “use strict” untuk setiap berkas asal.

    ECMAScript strict mode strict diperkenalkan di ES5 dan memberikan perubahan perilaku pada waktu proses mesin JavaScript untuk meningkatkan kinerja dan membuat kesalahan muncul agar diabaikan.

    • Recommended
    • Default:

      true if strict; false otherwise.

    • Related:
    • Released:

      2.1

    # Exact Optional Property Types - exactOptionalPropertyTypes

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

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

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

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

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

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

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

      4.4

    # No Fallthrough Cases In Switch - noFallthroughCasesInSwitch

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

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

    # No Implicit Any - noImplicitAny

    Di beberapa kasus, dimana tidak ada anotasi tipe yang ada, TypeScript akan kembali ke suatu tipe dari any untuk suatu variabel yang saat itu tidakbisa simpulkan tipenya.

    Ini dapat menyebabkan beberapa kesalahan untuk dilewatkan, sebagai contoh:

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

    Menyalakan opsi noImplicitAny namun TypeScript akan mengeluarkan kesalahan setiap kali any yang ia simpulkan:

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

      true if strict; false otherwise.

    • Related:

    # No Implicit Override - noImplicitOverride

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

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

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

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

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

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

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

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

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

    # No Implicit Returns - noImplicitReturns

    Saat diaktifkaan, TypeScript akan melakukan pengecekan semua jalur kode di suatu fungsi untuk memastikan mereka mengembalikan suatu nilai.

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

    # No Implicit This - noImplicitThis

    Menimbulkan kesalahan kepada pernyataan ‘this’ dengan tersiratnya tipe ‘any’.

    Sebagai contoh, class dibawah ini mengembalikan suatu fungsi yang mencoba mengakses this.width dan this.height – tapi konteksnya untuk this didalam fungsi yang didalam getAreaFunction ini, bukanlah instansi dari class Rectangle.

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

      true if strict; false otherwise.

    • Related:
    • Released:

      2.0

    # No Property Access From Index Signature - noPropertyAccessFromIndexSignature

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

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

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

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

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

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

    # No Unchecked Indexed Access - noUncheckedIndexedAccess

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

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

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

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

    # No Unused Locals - noUnusedLocals

    Report errors on unused local variables.

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

    # No Unused Parameters - noUnusedParameters

    Report errors on unused parameters in functions.

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

    # Strict - strict

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

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

    # Strict Bind Call Apply - strictBindCallApply

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

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

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

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

      true if strict; false otherwise.

    • Related:
    • Released:

      3.2

    # Strict Function Types - strictFunctionTypes

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

    Here’s a basic example with strictFunctionTypes off:

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

    With strictFunctionTypes on, the error is correctly detected:

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

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

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

      true if strict; false otherwise.

    • Related:
    • Released:

      2.6

    # Strict Null Checks - strictNullChecks

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

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

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

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

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

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

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

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

      true if strict; false otherwise.

    • Related:
    • Released:

      2.0

    # Strict Property Initialization - strictPropertyInitialization

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

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

    In the above case:

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

      true if strict; false otherwise.

    • Related:
    • Released:

      2.7

    # Use Unknown In Catch Variables - useUnknownInCatchVariables

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

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

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

    • Recommended
    • Default:

      true if strict; false otherwise.

    • Related:
    • Released:

      4.4

    #Modules

    # Allow Arbitrary Extensions - allowArbitraryExtensions

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

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

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

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

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

      # Allow Importing TS Extensions - allowImportingTsExtensions

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

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

        # Izinkan Akses Global Umd - allowUmdGlobalAccess

        Jika disetel ke true, allowUmdGlobalAccess memungkinkan Anda mengakses ekspor UMD sebagai global dari dalam berkas modul. Berkas modul adalah berkas yang telah diimpor dan/atau diekspor. Tanpa opsi ini, menggunakan ekspor dari modul UMD memerlukan deklarasi impor.

        Contoh kasus penggunaan untuk opsi ini adalah proyek web yang anda tahu bahwa pustaka tertentu (seperti jQuery atau Lodash) akan selalu tersedia saat runtime, tetapi Anda tidak dapat mengaksesnya dengan impor.

        # Base Url - baseUrl

        Memungkinkan Anda menyetel direktori dasar untuk menyelesaikan nama modul dengan benar.

        Anda dapat menentukan folder root di mana Anda dapat melakukan keputusan berkas yang sesungguhnya, misalnya :

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

        Dengan "baseUrl": "./" di dalam proyek ini TypeScript akan mencari berkas yang dimulai dari folder yang sama dengan tsconfig.json.

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

        Jika Anda lelah cara impor selalu seperti "../" atau "./". Atau harus untuk merubah saat Anda memindahkan berkas, ini adalah cara terbaik untuk memperbaikinya.

          # Custom Conditions - customConditions

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

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

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

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

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

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

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

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

          # Module - module

          Sets the module system for the program. See the theory behind TypeScript’s module option and its reference page for more information. You very likely want "nodenext" for modern Node.js projects and preserve or esnext for code that will be bundled.

          Changing module affects moduleResolution which also has a reference page.

          Here’s some example output for this file:

          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

          In addition to the base functionality of ES2015/ES6, ES2020 adds support for dynamic imports, and import.meta while ES2022 further adds support for top level await.

          node16/nodenext

          Available from 4.7+, the node16 and nodenext modes integrate with Node’s native ECMAScript Module support. The emitted JavaScript uses either CommonJS or ES2020 output depending on the file extension and the value of the type setting in the nearest package.json. Module resolution also works differently. You can learn more in the handbook and Modules Reference.

          preserve

          In --module preserve (added in TypeScript 5.4), ECMAScript imports and exports written in input files are preserved in the output, and CommonJS-style import x = require("...") and export = ... statements are emitted as CommonJS require and module.exports. In other words, the format of each individual import or export statement is preserved, rather than being coerced into a single format for the whole compilation (or even a whole file).

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

          While it’s rare to need to mix imports and require calls in the same file, this module mode best reflects the capabilities of most modern bundlers, as well as the Bun runtime.

          Why care about TypeScript’s module emit with a bundler or with Bun, where you’re likely also setting noEmit? TypeScript’s type checking and module resolution behavior are affected by the module format that it would emit. Setting module gives TypeScript information about how your bundler or runtime will process imports and exports, which ensures that the types you see on imported values accurately reflect what will happen at runtime or after bundling.

          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

          # Module Resolution - moduleResolution

          Specify the module resolution strategy:

          • 'node16' or 'nodenext' for modern versions of Node.js. Node.js v12 and later supports both ECMAScript imports and CommonJS require, which resolve using different algorithms. These moduleResolution values, when combined with the corresponding module values, picks the right algorithm for each resolution based on whether Node.js will see an import or require in the output JavaScript code.
          • 'node10' (previously called 'node') for Node.js versions older than v10, which only support CommonJS require. You probably won’t need to use node10 in modern code.
          • 'bundler' for use with bundlers. Like node16 and nodenext, this mode supports package.json "imports" and "exports", but unlike the Node.js resolution modes, bundler never requires file extensions on relative paths in imports.
          • 'classic' was used in TypeScript before the release of 1.6. classic should not be used.

          There are reference pages explaining the theory behind TypeScript’s module resolution and the details of each option.

          # Module Suffixes - moduleSuffixes

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

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

          Given the above configuration, an import like the following:

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

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

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

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

          # No Resolve - noResolve

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

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

            # Paths - paths

            A series of entries which re-map imports to lookup locations relative to the baseUrl if set, or to the tsconfig file itself otherwise. There is a larger coverage of paths in the moduleResolution reference page.

            paths lets you declare how TypeScript should resolve an import in your require/imports.

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

            This would allow you to be able to write import "jquery", and get all of the correct typing locally.

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

            In this case, you can tell the TypeScript file resolver to support a number of custom prefixes to find code.

            Note that this feature does not change how import paths are emitted by tsc, so paths should only be used to inform TypeScript that another tool has this mapping and will use it at runtime or when bundling.

              # Menyelesaikan Module JSON - resolveJsonModule

              Memperbolehkan mengimpor modul dengan ekstensi ‘.json’ merupakan praktik umum pada proyek node. Ini termasuk membuat jenis untuk import berdasarkan bentuk JSON statis.

              TypeScript tidak mendukung penyelesaian berkas JSON secara bawaan:

              ts
              // @filename: settings.json
              Cannot find module './settings.json'. Consider using '--resolveJsonModule' to import module with '.json' extension.2732Cannot find module './settings.json'. Consider using '--resolveJsonModule' to import module with '.json' extension.
              {
              "repo": "TypeScript",
              "dry": false,
              "debug": false
              }
              // @filename: index.ts
              import settings from "./settings.json";
               
              settings.debug === true;
              settings.dry === 2;
              Try

              Mengaktifkan opsi memungkinkan impor JSON, dan memvalidasi jenis dalam berkas JSON tersebut.

              ts
              // @filename: settings.json
              {
              "repo": "TypeScript",
              "dry": false,
              This comparison appears to be unintentional because the types 'boolean' and 'number' have no overlap.2367This comparison appears to be unintentional because the types 'boolean' and 'number' have no overlap.
              "debug": false
              }
              // @filename: index.ts
              import settings from "./settings.json";
               
              settings.debug === true;
              settings.dry === 2;
              Try

                # Resolve package.json Exports - resolvePackageJsonExports

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

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

                # Resolve package.json Imports - resolvePackageJsonImports

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

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

                # Root Dir - rootDir

                Bawaan: Jalur umum terpanjang dari semua berkas masukan non-deklarasi. Jika composite disetel, bawaannya adalah direktori yang berisi berkas tsconfig.json.

                Ketika TypeScript mengkompilasi berkas, ia mempertahankan struktur direktori yang sama pada direktori keluaran seperti struktur di direktori masukan.

                Misalnya, Anda memiliki beberapa berkas masukan:

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

                Kesimpulan untuk rootDir adalah jalur umum terpanjang dari semua berkas masukan non-deklarasi, yang dalam hal ini adalahcore/.

                Jika nilai outDir anda adalah dist, maka TypeScript akan membuat struktur direktori seperti ini:

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

                Namun, anda mungkin mengharapkan core menjadi bagian dari struktur direktori keluaran. Dengan menyetel rootDir: "." pada tsconfig.json, TypeScript akan menghasilkan struktur direktori seperti ini:

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

                Yang terpenting, rootDir tidak memengaruhi berkas mana yang menjadi bagian dari kompilasi. rootDir tidak memiliki hubungan dengan pengaturan include, exclude, atau files pada tsconfig.json

                Perhatikan bahwa TypeScript tidak akan pernah menulis berkas keluaran (file output) ke direktori di luar dari outDir, dan tidak akan pernah melewatkan pengeluaran berkas. Karena alasan ini, rootDir mengharuskan semua berkas yang perlu dikeluarkan berada dibawah jalur rootDir.

                Misalnya, Anda memiliki struktur direktori seperti ini:

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

                Ini akan menimbulkan galat ketika menentukan rootDir sebagai core dan include sebagai * karena ini membuat berkas (helpers.ts) yang perlu diletakkan di luar dari outDir (yaitu ../helpers.js)

                • Default:

                  Computed from the list of input files.

                • Released:

                  1.5

                # Root Dirs - rootDirs

                Dengan menggunakan rootDirs, Anda dapat memberi tahu kompilator bahwa ada banyak direktori “virtual” yang bertindak sebagai salah satu akar (root). Hal ini memungkinkan kompilator untuk menyelesaikan impor pada modul relatif dalam direktori “virtual”, seolah-olah digabungkan menjadi satu direktori.

                Sebagai contoh:

                src └── views └── view1.ts (bisa impor "./template1", "./view2`) └── view2.ts (bisa impor "./template1", "./view1`) generated └── templates └── views └── template1.ts (bisa impor "./view1", "./view2")
                {
                "": ["src/views", "generated/templates/views"]
                }
                }

                Ini tidak memengaruhi bagaimana Typescript menghasilkan Javascript, ini hanya mengemulasi asumsi bahwa mereka akan mampu melakukan perkerjaan melalui Jalur relatif tersebut saat runtime.

                • Default:

                  Computed from the list of input files.

                • Released:

                  2.0

                # Type Roots - typeRoots

                By default all visible@types” packages are included in your compilation. Packages in node_modules/@types of any enclosing folder are considered visible. For example, that means packages within ./node_modules/@types/, ../node_modules/@types/, ../../node_modules/@types/, and so on.

                If typeRoots is specified, only packages under typeRoots will be included. For example:

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

                This config file will include all packages under ./typings and ./vendor/types, and no packages from ./node_modules/@types. All paths are relative to the tsconfig.json.

                # Types - types

                Secara default, semua visible package@types” diikutsertakan dalam kompilasi Anda. Package dalam node_modules/@types yang terletak dalam folder lain dianggap sebagai visible. Sebagai contoh, package yang berada di ./node_modules/@types/, ../node_modules/@types/, ../../node_modules/@types/, dan seterusnya dianggap sebagai visible.

                Jika types telah ditentukan, hanya package yang didaftarkan yang akan disertakan pada lingkup global, misalnya:

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

                Berkas tsconfig.json ini hanya akan menyertakan ./node_modules/@types/node, ./node_modules/@types/jest dan ./node_modules/@types/express. Package lainnya di bawah direktori node_modules/@types/* tidak akan diikutsertakan.

                Apa dampaknya?

                Opsi ini tidak memengaruhi bagaimana @types/* diikutsertakan dalam kode aplikasi Anda, Sebagai contoh, apabila Anda memiliki compilerOptions seperti di pada contoh di atas dan kode seperti berikut:

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

                Import moment akan sepenuhnya diketik.

                Ketika Anda memiliki opsi ini pada pengaturan tanpa menyertakan sebuah modul dalam array types, maka:

                • globals tidak akan ditambahkan ke dalam proyek Anda (contoh: process pada node atau expect pada Jest)
                • Ekspor tidak akan muncul sebagai rekomendasi auto-import

                Pengaturan pada fitur ini hanya tentang menentukan types yang ingin Anda sertakan, sedangkan typeRoots mendukung apabila Anda hanya menginginkan folder-folder tertentu saja.

                #Emit

                # Declaration - declaration

                Buat berkas .d.ts untuk setiap berkas TypeScript atau JavaScript di dalam proyek Anda. Berkas .d.ts ini adalah berkas definisi tipe yang menjelaskan API eksternal modul Anda. Dengan berkas .d.ts, alat seperti TypeScript dapat menyediakan tipe yang masuk akal di dalam sumber kode tanpa definisi tipe data.

                Jika declaration disetel ketrue, jalankan compiler dengan kode TypeScript:

                ts
                export let helloWorld = "hi";
                Try

                Akan menghasilkan berkas index.js seperti ini:

                ts
                export let helloWorld = "hi";
                 
                Try

                Dengan helloWorld.d.ts yang sesuai:

                ts
                export declare let helloWorld: string;
                 
                Try

                Saat bekerja dengan berkas .d.ts untuk file JavaScript, Anda mungkin ingin menggunakan emitDeclarationOnly atau menggunakan outDir untuk memastikan bahwa berkas JavaScript tidak ditimpa.

                # Declaration Dir - declarationDir

                Menawarkan cara untuk mengonfigurasi direktori root tempat berkas deklarasi dihasilkan.

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

                dengan tsconfig.json;

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

                Akan menempatkan d.ts untuk index.ts di direktori types:

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

                # _Declaration Map_ - declarationMap

                Menghasilkan peta sumber untuk berkas .d.ts yang mengarahkan kembali ke berkas sumber .ts asli. Ini akan memungkinkan editor seperti VS Code untuk pergi ke file .ts asli saat menggunakan fitur seperti Go to Definition.

                Anda harus mempertimbangkan untuk mengaktifkan ini jika Anda menggunakan referensi proyek.

                # Iterasi tingkat bawah - downlevelIteration

                Downleveling adalah istilah TypeScript untuk mentranspilasi ke versi JavaScript yang lebih lama. Saran ini untuk mengaktifkan dukungan implementasi yang lebih akurat tentang bagaimana JavaScript modern melakukan iterasi melalui konsep baru di runtime JavaScript yang lebih lama.

                ECMAScript 6 menambahkan beberapa iterasi primitif baru: loop for / of (for (el of arr)), Array spread ([a, ...b]), penyebaran argumen (fn(...args)), dan Symbol.iterator. --downlevelIteration memungkinkan iterasi primitif ini digunakan secara lebih akurat dalam lingkungan ES5 jika ada implementasi Symbol.iterator.

                Contoh: Efek pada for / of

                Tanpa downlevelIteration aktif, loop for / of pada objek apa pun diturunkan levelnya menjadi loop for tradisional:

                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

                Hal ini sering kali diharapkan orang, tetapi tidak 100% sesuai dengan perilaku ECMAScript 6. String tertentu, seperti emoji (😜), memiliki .length 2 (atau bahkan lebih!), Tetapi harus diiterasi sebagai 1 unit dalam loop for-of. Lihat postingan blog oleh Jonathan New untuk penjelasan yang lebih lengkap.

                Jika downlevelIteration diaktifkan, TypeScript akan menggunakan fungsi bantuan yang memeriksa implementasi Symbol.iterator (baik native maupun polyfill). Jika implementasi ini hilang, Anda akan kembali ke iterasi berbasis indeks.

                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

                Catatan: memungkinkan downlevelIteration tidak meningkatkan kepatuhan jika Symbol.iterator tidak ada saat runtime.

                Contoh: Efek pada Array Spreads

                ini adalah array spread:

                js
                // Buat array baru yang elemennya 1 diikuti dengan elemen arr2
                const arr = [1, ...arr2];

                Berdasarkan uraian tersebut, sepertinya mudah untuk menurunkan ke ES5:

                js
                // Sama kan?
                const arr = [1].concat(arr2);

                Namun, ini sangat berbeda dalam kasus tertentu yang jarang terjadi. Misalnya, jika sebuah array memiliki “lubang” di dalamnya, indeks yang hilang akan membuat properti own jika disebarkan, tetapi tidak akan jika dibuat menggunakan concat:

                js
                // Buatlah array dimana elemen '1' hilang
                let missing = [0, , 1];
                let spreaded = [...missing];
                let concated = [].concat(missing);
                // benar
                "1" in spreaded;
                // salah
                "1" in concated;

                Seperti halnya dengan for / of, downlevelIteration akan menggunakan Symbol.iterator (jika ada) untuk meniru perilaku ES 6 dengan lebih akurat.

                # _Emit BOM_ - emitBOM

                Mengontrol apakah TypeScript akan menghasilkan tanda urutan byte (byte order mark - BOM) saat menulis berkas output. Beberapa lingkungan runtime memerlukan BOM untuk menafsirkan berkas JavaScript dengan benar; yang lain mengharuskan itu tidak ada. Nilai bawaan dari false umumnya paling baik kecuali Anda memiliki alasan untuk mengubahnya.

                  # Menghasilkan Deklarasi Saja - emitDeclarationOnly

                  Hanya menghasilkan berkas .d.ts; jangan mengirimkan berkas .js.

                  Pengaturan ini berguna dalam dua kasus:

                  • Anda menggunakan transpiler selain TypeScript untuk membuat JavaScript Anda.
                  • Anda menggunakan TypeScript hanya untuk menghasilkan berkas d.ts untuk konsumen Anda.

                  # Import Helpers - importHelpers

                  Untuk operasi penurunan tingkat tertentu, TypeScript menggunakan beberapa kode penunjang untuk operasi seperti memperluas kelas, himpunan(spread) susunan atau objek, dan menyambungkan operasi. Secara umum, penunjang ini dimasukkan ke dalam berkas yang menggunakannya. Ini dapat mengakibatkan duplikasi kode jika penunjang yang sama digunakan di banyak berkas yang berbeda.

                  Jika importHelpers kode ini aktif, fungsi penunjang ini diimpor dari tslib modul. Anda perlu memastikan bahwa berkas tslib modul dapat diimpor saat dijalankan. Ini hanya mempengaruhi modul, berkas kode tidak akan mencoba mengimpor modul.

                  Misalnya, dengan TypeScript:

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

                  Memasang downlevelIteration dan importHelpers masih salah:

                  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

                  Lalu aktifkan keduanya downlevelIteration dan importHelpers:

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

                  Anda bisa menggunakan noEmitHelpers saat menyediakan implementasi untuk fungsi-fungsi ini.

                  # Impor Tidak Digunakan Sebagai Nilai - importsNotUsedAsValues

                  Kode ini mengontrol cara kerja import, ada 3 opsi berbeda:

                  • remove: Perilaku umum untuk menghapus pernyataan import yang hanya merupakan acuan dari kata.

                  • preserve: Mempertahankan semua pernyataan import yang nilai atau katanya tidak pernah digunakan. Hal ini dapat menyebabkan impor/efek samping yang tetap dipertahankan.

                  • error: Ini mempertahankan semua impor (sama seperti pilihan), tetapi akan mengalami galat jika impor nilai hanya digunakan sebagai tipe data. Ini mungkin berguna jika Anda ingin memastikan tidak ada nilai yang diimpor secara tidak sengaja, tetapi tetap membuat impor dengan jelas.

                  Kode ini berfungsi karena Anda dapat menggunakan import type secara jelas dengan pernyataan import yang tidak boleh dimasukkan ke JavaScript.

                  # Peta Sumber Sebaris - inlineSourceMap

                  Jika disetel, ketika menulis berkas .js.map untuk menyediakan peta sumber, TypeScript akan menyematkan konten peta sumber di berkas .js. Meskipun ini menghasilkan berkas JS yang lebih besar, tapi dapat memudahkan dalam beberapa tahap. Misalnya anda mungkin ingin mencoba berkas JS pada server web, tapi tidak mengizinkan berkas .map untuk ditampilkan.

                  Saling terpisah dengan sourceMap.

                  Misalnya, dengan TypeScript:

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

                  Di ubah menjadi JavaScript:

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

                  Kemudian aktifkan pembuatannya dengan inlineSourceMap, ada komentar di bagian bawah berkas yang menyertakan peta sumber untuk berkas tersebut.

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

                  # Sumber Sebaris - inlineSources

                  Jika dilihat, TypeScript akan menyertakan konten asli dari berkas .ts sebagai string yang disematkan di peta sumber. Ini sering kali berguna dalam kasus yang sama seperti inlineSourceMap.

                  Membutuhkan sourceMap atau inlineSourceMap untuk disetel.

                  Misalnya, dengan TypeScript:

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

                  Di ubah menjadi JavaScript:

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

                  Kemudian dengan inlineSources dan inlineSourceMap diaktifkan, ada komentar di bagian bawah berkas yang menyertakan peta sumber untuk berkas tersebut. Perhatikan bahwa ada yang berbeda di akhir [inlineSourceMap] (# inlineSourceMap) karena peta sumber sekarang berisi kode sumber asli.

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

                  # Map Root - mapRoot

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

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

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

                    # New Line - newLine

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

                    • Default:

                      Platform specific.

                    • Allowed:
                      • crlf

                      • lf

                    • Released:

                      1.5

                    # No Emit - noEmit

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

                    This makes room for another tool like Babel, or swc to handle converting the TypeScript file to a file which can run inside a JavaScript environment.

                    You can then use TypeScript as a tool for providing editor integration, and as a source code type-checker.

                      # No Emit Helpers - noEmitHelpers

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

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

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

                      Which creates quite a lot of JavaScript:

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

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

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

                      # No Emit On Error - noEmitOnError

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

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

                      # Out Dir - outDir

                      Jika ditentukan, berkas-berkas .js (maupun .d.ts, .js.map, dsb.) akan disertakan ke dalam direktori ini. Struktur direktori dari sumber awal berkas-berkas juga dipertahankan; lihat rootDir jika akar yang di perhitungkan bukan yang anda inginkan.

                      Jika tidak ditentukan, berkas-berkas .js akan disertakan di direktori yang sama dengan berkas-berkas .ts dari mana mereka di hasilkan:

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

                      Dengan suatu tsconfig.json seperti ini:

                      {
                      "": "dist"
                      }
                      }

                      Menjalankan tsc dengan pengaturan ini dapat memindahkan berkas-berkas ke direktori dist:

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

                      # Out File - outFile

                      Jika ditentukan, semua berkas global (non-module) akan digabung menjadi satu berkas keluaran tertentu.

                      Jika module adalah system atau amd, semua berkas modul juga akan digabungkan menjadi berkas ini setelah semua konten global.

                      Catatan: outFile tidak dapat digunakan kecuali module adalah None, System, atau AMD. Opsi ini tidak bisa digunakan untuk membundel modul CommonJS atau ES6.

                      # Preserve Const Enums - preserveConstEnums

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

                      For example with this TypeScript:

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

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

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

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

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

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

                      # Preserve Value Imports - preserveValueImports

                      Deprecated in favor of verbatimModuleSyntax.

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

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

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

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

                      # Menghapus Komentar - removeComments

                      Menghapus semua komentar pada berkas Typescript pada saat mengonversi ke berkas Javascript. Pengaturan bawaannya adalah false

                      Sebagai contoh, ini adalah berkas TypeScript yang memiliki komentar JSDoc:

                      ts
                      /** Terjemahan dari 'Hello world' ke bahasa Indonesia */
                      export const helloWorldID = "Halo Dunia";

                      Ketika removeComments disetel ke true:

                      ts
                      export const helloWorldID = "Halo Dunia";
                       
                      Try

                      Tanpa menyetel removeComments atau menjadikannya sebagai false:

                      ts
                      /** Terjemahan dari 'Hello world' ke bahasa Indonesia */
                      export const helloWorldID = "Halo Dunia";
                       
                      Try

                      Artinya, komentar anda akan muncul di kode Javascript

                        # Source Map - sourceMap

                        Enables the generation of sourcemap files. These files allow debuggers and other tools to display the original TypeScript source code when actually working with the emitted JavaScript files. Source map files are emitted as .js.map (or .jsx.map) files next to the corresponding .js output file.

                        The .js files will in turn contain a sourcemap comment to indicate where the files are to external tools, for example:

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

                        Compiling with sourceMap set to true creates the following JavaScript file:

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

                        And this also generates this json map:

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

                          # Source Root - sourceRoot

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

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

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

                            # Strip Internal - stripInternal

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

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

                            With the flag set to false (default):

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

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

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

                            The JavaScript output is still the same.

                            • Internal

                            #JavaScript Support

                            # Allow JS - allowJs

                            Izinkan berkas JavaScript diimpor ke dalam proyek Anda, bukan hanya berkas .ts dan.tsx. Contoh, berkas JS ini:

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

                            Ketika diimpor ke berkas TypeScript akan menimbulkan galat seperti berikut:

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

                            Impor berkas akan baik-baik saja saat allowJs diaktifkan:

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

                            Opsi ini dapat digunakan sebagai cara untuk menambahkan berkas TypeScript secara bertahap ke dalam proyek JS dengan mengizinkan berkas .ts dan.tsx untuk hidup berdampingan dengan berkas JavaScript yang ada.

                            # Check JS - checkJs

                            Bekerja sama dengan allowJs. Kapan checkJs diaktifkan kemudian kesalahan dilaporkan dalam berkas JavaScript. Ini termasuk // @ts-check di bagian atas semua berkas JavaScript yang disertakan dalam proyek Anda.

                            Misalnya, ini adalah JavaScript yang salah menurut definisi jenis parseFloat yang disertakan dengan TypeScript:

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

                            Saat diimpor ke modul TypeScript:

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

                            Anda tidak akan mendapatkan kesalahan apapun. Namun, jika Anda mengaktifkan checkJs maka Anda akan mendapatkan pesan kesalahan dari berkas JavaScript.

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

                            # Max Node Module JS Depth - maxNodeModuleJsDepth

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

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

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

                              #Editor Support

                              # Nonaktifkan Batas Ukuran - disableSizeLimit

                              Untuk menghindari kemungkinan masalah pembengkakan memori saat bekerja dengan proyek JavaScript yang sangat besar, ada batas atas jumlah memori yang akan dialokasikan TypeScript. Mengaktifkan saran ini akan menghapus batas.

                                # Plugins - plugins

                                List of language service plugins to run inside the editor.

                                Language service plugins are a way to provide additional information to a user based on existing TypeScript files. They can enhance existing messages between TypeScript and an editor, or to provide their own error messages.

                                For example:

                                VS Code has the ability for a extension to automatically include language service plugins, and so you may have some running in your editor without needing to define them in your tsconfig.json.

                                  #Interop Constraints

                                  # Izinkan Setelan Standar Impor Sintetis - allowSyntheticDefaultImports

                                  Jika disetel ke true allowSyntheticDefaultImports memungkinkan Anda untuk menulis impor seperti:

                                  ts
                                  import React from "react";

                                  daripada:

                                  ts
                                  import * as React from "react";

                                  Jika modul tidak secara eksplisit menentukan ekspor default.

                                  Misalnya, tanpaallowSyntheticDefaultImports disetel ke true:

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

                                  Kode ini menimbulkan galat karena tidak ada objek default yang dapat Anda impor. Meski rasanya seperti itu seharusnya. Untuk kenyamanan, transpiler seperti Babel akan secara otomatis membuat setelan standar jika tidak dibuat. Membuat modul terlihat lebih seperti:

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

                                  Opsi ini tidak memengaruhi JavaScript yang dihasilkan oleh TypeScript, ini hanya untuk type checking. Opsi ini membuat perilaku TypeScript sejalan dengan Babel, di mana kode ekstra akan ditambahkan kedalam setelan standar ekspor untuk membuat sebuah modul lebih ergonomis.

                                  # Interop Modul ES - esModuleInterop

                                  Secara bawaan (dengan esModuleInterop false atau tidak disetel) TypeScript memperlakukan modul CommonJS/AMD/UMD mirip dengan modul ES6. Dalam melakukan ini, ada dua bagian tertentu yang ternyata merupakan asumsi yang salah:

                                  • Impor namespace seperti import * as moment from "moment" bertindak sama seperti const moment = require("moment")

                                  • Impor bawaan seperti import moment from "moment" berfungsi sama seperti const moment = require("moment").default

                                  Ketidakcocokan ini menyebabkan dua masalah berikut:

                                  • Spesifikasi modul ES6 menyatakan bahwa impor namespace (import * as x) hanya dapat menjadi objek, dengan memiliki TypeScript memperlakukannya sama dengan = require ("x") maka TypeScript diizinkan untuk impor diperlakukan sebagai fungsi dan dapat dipanggil. Ini melanggar rekomendasi spesifikasi.

                                  • Meskipun akurat untuk spesifikasi modul ES6, sebagian besar pustaka dengan modul CommonJS/AMD/UMD tidak seketat implementasi TypeScript.

                                  Mengaktifkan esModuleInterop akan memperbaiki kedua masalah ini dalam kode yang ditranspilasi oleh TypeScript. Perubahan pertama perilaku di kompilator, yang kedua diperbaiki oleh dua fungsi pembantu baru yang menyediakan shim untuk memastikan kompatibilitas dalam JavaScript yang dihasilkan:

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

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

                                  Dengan esModuleInterop disetel ke true:

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

                                  Catatan: Anda dapat meminimalisir ukuran keluaran dengan mengaktifkan importHelpers:

                                  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

                                  Mengaktifkan esModuleInterop juga akan mengaktifkan allowSyntheticDefaultImports.

                                  # Paksa Jenis Huruf Konsisten Dalam Nama berkas - forceConsistentCasingInFileNames

                                  TypeScript mengikuti aturan sensitifitas huruf besar dari sistem berkas yang menjalankannya. Ini bisa menjadi masalah jika beberapa pengembang bekerja dalam sistem berkas sensitifitas huruf besar dan kecil dan yang lainnya tidak. Jika sebuah berkas mencoba mengimpor fileManager.ts dengan menetapkan ./FileManager.ts, berkas tersebut akan ditemukan dalam sistem berkas yang tidak peka huruf besar/kecil, tetapi tidak pada sistem berkas yang peka huruf besar kecil.

                                  Ketika opsi ini disetel, TypeScript akan mengeluarkan galat jika program mencoba memasukkan berkas dengan jenis huruf yang berbeda dari jenis huruf pada disk.

                                  • Recommended
                                  • Default:

                                    true

                                  # Modul Terisolasi (_Isolated Modules_) - isolatedModules

                                  Meskipun Anda dapat menggunakan TypeScript untuk menghasilkan ke kode JavaScript, penggunaan transpiler lain seperti Babel juga umum untuk dilakukan. Namun, transpiler lain hanya beroperasi di satu berkas pada satu waktu, yang berarti mereka tidak dapat menerapkan transformasi kode yang bergantung pada pemahaman sistem tipe penuh. Pembatasan ini juga berlaku untuk API ts.transpileModule TypeScript yang digunakan oleh beberapa alat pengembang.

                                  Batasan ini dapat menyebabkan masalah waktu proses dengan beberapa fitur TypeScript seperti const enums dan namespaces. Pilihan isolatedModules memberi tahu TypeScript untuk memperingatkan Anda jika menulis kode tertentu yang tidak dapat diartikan dengan benar oleh proses transpilasi berkas tunggal.

                                  Itu tidak mengubah kode Anda atau mengubah perilaku proses pemeriksaan dan pengecekan kode TypeScript.

                                  Beberapa contoh kode yang tidak berfungsi saat isolatedModules diaktifkan.

                                  Ekspor Pengenal Non-Nilai

                                  Di TypeScript, Anda dapat mengimpor type dan kemudian mengekspornya:

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

                                  Karena tidak ada nilai untuk someType, export yang ditampilkan tidak akan mencoba mengekspornya (ini akan menjadi galat waktu proses di JavaScript):

                                  js
                                  export { someFunction };

                                  Transpiler satu berkas tidak tahu apakah someType menghasilkan nilai atau tidak, jadi itu adalah galat untuk mengekspor nama yang hanya mengacu pada sebuah tipe.

                                  Non-Module Files

                                  Jika isolatedModules dipilih, semua berkas implementasi harus dalam modules (yang berarti memiliki beberapa bentuk import / export). galat terjadi jika berkas:

                                  ts
                                  function fn() {}
                                  Try

                                  Pembatasan ini tidak berlaku untuk berkas .d.ts

                                  Referensi ke anggota const enum

                                  Di TypeScript, saat mereferensikan anggota const enum, referensi tersebut diganti dengan nilai sebenarnya di JavaScript yang ditampilkan.

                                  Mengubah TypeScript:

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

                                  Ini untuk JavaScript:

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

                                  Tanpa pengetahuan tentang nilai anggota ini, transpiler lain tidak dapat menggantikan referensi ke Number, yang akan menjadi galat dijalankan jika dibiarkan (karena tidak ada objek Numbers pada waktu proses). Karena itu, ketika isolatedModules dipilih, akan terjadi galat yang mereferensikan anggota const enum di sekelilingnya.

                                    This is to reflect the same flag in Node.js; which does not resolve the real path of symlinks.

                                    This flag also exhibits the opposite behavior to Webpack’s resolve.symlinks option (i.e. setting TypeScript’s preserveSymlinks to true parallels setting Webpack’s resolve.symlinks to false, and vice-versa).

                                    With this enabled, references to modules and packages (e.g. imports and /// <reference type="..." /> directives) are all resolved relative to the location of the symbolic link file, rather than relative to the path that the symbolic link resolves to.

                                      # Verbatim Module Syntax - verbatimModuleSyntax

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                        #Backwards Compatibility

                                        # Charset - charset

                                        Di TypeScript versi sebelumnya, ini mengontrol pengkodean yang digunakan saat membaca berkas teks dari memori. Saat ini, TypeScript mengasumsikan pengkodean UTF-8, tetapi akan mendeteksi dengan benar UTF-16 (BE dan LE) atau UTF-8 BOMs.

                                        • Deprecated
                                        • Default:

                                          utf8

                                        # Keyof Strings Only - keyofStringsOnly

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

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

                                        • Deprecated
                                        • Released:

                                          2.9

                                        # No Implicit Use Strict - noImplicitUseStrict

                                        Anda seharusnya tidak memerlukan ini. Secara bawaan, saat memancarkan sebuah berkas modul kepada sebuah target non-ES6, TypeScript memancarkan sebuah kata pengantar "use strict"; di bagian atas berkas. Ini dapat menonaktifkan setelan kata pengantar itu.

                                          # No Strict Generic Checks - noStrictGenericChecks

                                          TypeScript will unify type parameters when comparing two generic functions.

                                          ts
                                          type A = <T, U>(x: T, y: U) => [T, U];
                                          type B = <S>(x: S, y: S) => [S, S];
                                           
                                          function f(a: A, b: B) {
                                          b = a; // Ok
                                          a = b; // Error
                                          Type 'B' is not assignable to type 'A'. Types of parameters 'y' and 'y' are incompatible. Type 'U' is not assignable to type 'T'. 'T' could be instantiated with an arbitrary type which could be unrelated to 'U'.2322Type 'B' is not assignable to type 'A'. Types of parameters 'y' and 'y' are incompatible. Type 'U' is not assignable to type 'T'. 'T' could be instantiated with an arbitrary type which could be unrelated to 'U'.
                                          }
                                          Try

                                          This flag can be used to remove that check.

                                          # Out - out

                                          Gunakan outFile sebagai gantinya.

                                          Opsi out memproses lokasi akhir dengan dengan cara yang tidak dapat diprediksi atau konsisten. Opsi ini dipertahankan hanya untuk kompatibilitas dengan versi lama dan sudah usang.

                                          # Suppress Excess Property Errors - suppressExcessPropertyErrors

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

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

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

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

                                            # Suppress Implicit Any Index Errors - suppressImplicitAnyIndexErrors

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

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

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

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

                                            #Language and Environment

                                            # Menghasilkan Dekorator Metadata - emitDecoratorMetadata

                                            Mengaktifkan dukungan eksperimental untuk menghasilkan tipe data metadata untuk dekorator yang bekerja dengan modul reflect-metadata.

                                            Sebagai contoh, berikut adalah JavaScript

                                            ts
                                            function LogMethod(
                                            target: any,
                                            propertyKey: string | symbol,
                                            descriptor: PropertyDescriptor
                                            ) {
                                            console.log(target);
                                            console.log(propertyKey);
                                            console.log(descriptor);
                                            }
                                             
                                            class Demo {
                                            @LogMethod
                                            public foo(bar: number) {
                                            // do nothing
                                            }
                                            }
                                             
                                            const demo = new Demo();
                                            Try

                                            Dengan emitDecoratorMetadata tidak disetel ke true (bawaan):

                                            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

                                            Dengan emitDecorationMetadata di setel ke true:

                                            ts
                                            "use strict";
                                            var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
                                            var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
                                            if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
                                            else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
                                            return c > 3 && r && Object.defineProperty(target, key, r), r;
                                            };
                                            var __metadata = (this && this.__metadata) || function (k, v) {
                                            if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
                                            };
                                            function LogMethod(target, propertyKey, descriptor) {
                                            console.log(target);
                                            console.log(propertyKey);
                                            console.log(descriptor);
                                            }
                                            class Demo {
                                            foo(bar) {
                                            // 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

                                            # Decorators Eksperimental - experimentalDecorators

                                            Menyalakan dukungan eksperimental untuk decorator, yang terdapat pada tahap ke 2 proses standarisasi TC39.

                                            Decorator adalah fitur bahasa pemrograman yang belum diadaptasi secara penuh ke dalam spesifikasi JavaScript. Hal ini berarti bahwa versi implementasi di TypeScript mungkin berbeda dengan implementasi pada JavaScript ketika fitur tersebut telah diputuskan oleh TC39.

                                            Anda dapat mencari tahu lebih lanjut mengenai dukungan decorator di TypeScript pada buku petunjuk.

                                            # JSX - jsx

                                            Mengatur bagaimana konstruksi JSX dihasilkan di dalam file Javascript. Ini hanya akan berpengaruh pada keluaran file JS yang dimulai di file .tsx.

                                            • react: Menghasilkan file .js dengan JSX yang diubah seperti pemanggilan React.createElement
                                            • preserve: Menghasilkan file .jsx tanpa mengubah JSX
                                            • react-native: Menghasilkan file .jsx tanpa mengubah JSX

                                            # JSX Factory - jsxFactory

                                            Mengubah fungsi yang dipanggil pada file .js ketika melakukan kompilasi elemen-elemen JSX. Perubahan yang paling umum adalah dengan menggunakan "h" atau "preact.h" dibandingkan penggunaan bawaan "React.createElement" jika menggunakan preact.

                                            Opsi ini dapat digunakan pada basis per file juga seperti halnya Babel’s /** @jsx h */ directive.

                                            # jsxFragmentFactory - jsxFragmentFactory

                                            Menentukan fungsi penghasil fragmen JSX yang akan digunakan ketika menargetkan kompiler react JSX jsxFactory sudah ditentukan, misalnya seperti Fragment.

                                            Opsi ini dapat digunakan pada basis per file juga seperti halnya Babel’s /** @jsxFrag h */ directive.

                                            Contoh dengan menggunakan TSConfig berikut ini:

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

                                            TSX file berikut:

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

                                            Akan terlihat seperti:

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

                                            # JSX Import Source - jsxImportSource

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

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

                                            For example with this code:

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

                                            Using this TSConfig:

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

                                            The emitted JavaScript from TypeScript is:

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

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

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

                                            Which generates code like:

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

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

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

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

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

                                            # Lib - lib

                                            TypeScript includes a default set of type definitions for built-in JS APIs (like Math), as well as type definitions for things found in browser environments (like document). TypeScript also includes APIs for newer JS features matching the target you specify; for example the definition for Map is available if target is ES6 or newer.

                                            You may want to change these for a few reasons:

                                            • Your program doesn’t run in a browser, so you don’t want the "dom" type definitions
                                            • Your runtime platform provides certain JavaScript API objects (maybe through polyfills), but doesn’t yet support the full syntax of a given ECMAScript version
                                            • You have polyfills or native implementations for some, but not all, of a higher level ECMAScript version

                                            In TypeScript 4.5, lib files can be overridden by npm modules, find out more in the blog.

                                            High Level libraries

                                            Name Contents
                                            ES5 Core definitions for all ES3 and ES5 functionality
                                            ES2015 Additional APIs available in ES2015 (also known as ES6) - array.find, Promise, Proxy, Symbol, Map, Set, Reflect, etc.
                                            ES6 Alias for “ES2015”
                                            ES2016 Additional APIs available in ES2016 - array.include, etc.
                                            ES7 Alias for “ES2016”
                                            ES2017 Additional APIs available in ES2017 - Object.entries, Object.values, Atomics, SharedArrayBuffer, date.formatToParts, typed arrays, etc.
                                            ES2018 Additional APIs available in ES2018 - async iterables, promise.finally, Intl.PluralRules, regexp.groups, etc.
                                            ES2019 Additional APIs available in ES2019 - array.flat, array.flatMap, Object.fromEntries, string.trimStart, string.trimEnd, etc.
                                            ES2020 Additional APIs available in ES2020 - string.matchAll, etc.
                                            ES2021 Additional APIs available in ES2021 - promise.any, string.replaceAll etc.
                                            ES2022 Additional APIs available in ES2022 - array.at, RegExp.hasIndices, etc.
                                            ESNext Additional APIs available in ESNext - This changes as the JavaScript specification evolves
                                            DOM DOM definitions - window, document, etc.
                                            WebWorker APIs available in WebWorker contexts
                                            ScriptHost APIs for the Windows Script Hosting System

                                            Individual library components

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

                                            This list may be out of date, you can see the full list in the TypeScript source code.

                                            # Module Detection - moduleDetection

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

                                            There are three choices:

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

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

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

                                            • Default:

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

                                            • Allowed:
                                              • legacy

                                              • auto

                                              • force

                                            • Released:

                                              4.7

                                            # No Lib - noLib

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

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

                                            # React Namespace - reactNamespace

                                            Gunakan --jsxFactory sebagai gantinya. Tentukan objek yang dipanggil oleh createElement ketika menargetkan react pada berkas TSX.

                                            • Default:

                                              React

                                            # Target - target

                                            Beberapa browser modern mendukung semua fitur ES6, jadi ES6 merupakan pilihan yang baik. Anda dapat memilih untuk menyetel sasaran yang lebih rendah apabila kode Anda diluncurkan untuk lingkungan yang lebih lama, atau sebuah sasaran yang lebih tinggi apabila kode Anda dijamin untuk dapat berjalan di lingkungan yang lebih baru.

                                            Pengaturan target mengubah fitur JS mana yang diturunkan levelnya dan mana yang dibiarkan utuh. Sebagai contoh, sebuah arrow_function () => this akan berubah menjadi sebuah ekspresi yang ekuivalen dengan function apabila target merupakan ES5 atau versi yang lebih rendah.

                                            Mengubah target berarti juga mengubah nilai default dari lib. Anda dapat mengatur target danlib sesuai keinginan, tetapi Anda dapat menyetel target untuk alasan kenyamanan.

                                            Jika Anda hanya bekerja dengan Node.js, berikut adalah beberapa target yang direkomendasikan berdasarkan versi Node:

                                            Nama Target yang didukung
                                            Node 8 ES2017
                                            Node 10 ES2018
                                            Node 12 ES2019

                                            Ini didasarkan pada database dukungan node.green.

                                            Nilai khusus ESNext merujuk pada versi tertinggi yang didukung oleh versi TypeScript Anda. Pengaturan ini harus dilakukan secara hati-hati, karena ini tidak berarti hal yang sama pada versi TypeScript yang berbeda dan dapat membuat peningkatan kurang dapat diprediksi.

                                            • Default:

                                              ES3

                                            • Allowed:
                                              • es3

                                              • es5

                                              • es6/es2015

                                              • es2016

                                              • es2017

                                              • es2018

                                              • es2019

                                              • es2020

                                              • es2021

                                              • es2022

                                              • esnext

                                            • Released:

                                              1.0

                                            # Use Define For Class Fields - useDefineForClassFields

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

                                            This flag switches to the upcoming ECMA runtime behavior.

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

                                            • Default:

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

                                            • Released:

                                              3.7

                                            #Compiler Diagnostics

                                            # Diagnostics - diagnostics

                                            Digunakan untuk mengeluarkan informasi diagnostik untuk debugging. Perintah ini adalah subset dari extendedDiagnostics yang lebih merupakan hasil yang dilihat pengguna, dan lebih mudah ditafsirkan.

                                            Jika Anda telah diminta oleh kompilator engineer TypeScript untuk memberikan hasil menggunakan tanda ini dalam sebuah kompilasi, di mana tidak ada salahnya menggunakan --extendedDiagnostics sebagai gantinya.

                                            # Explain Files - explainFiles

                                            Print names of files which TypeScript sees as a part of your project and the reason they are part of the compilation.

                                            For example, with this project of just a single index.ts file

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

                                            Using a tsconfig.json which has explainFiles set to true:

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

                                            Running TypeScript against this folder would have output like this:

                                            ❯ tsc node_modules/typescript/lib/lib.d.ts Default library for target 'es5' node_modules/typescript/lib/lib.es5.d.ts Library referenced via 'es5' from file 'node_modules/typescript/lib/lib.d.ts' node_modules/typescript/lib/lib.dom.d.ts Library referenced via 'dom' from file 'node_modules/typescript/lib/lib.d.ts' node_modules/typescript/lib/lib.webworker.importscripts.d.ts Library referenced via 'webworker.importscripts' from file 'node_modules/typescript/lib/lib.d.ts' node_modules/typescript/lib/lib.scripthost.d.ts Library referenced via 'scripthost' from file 'node_modules/typescript/lib/lib.d.ts' index.ts Matched by include pattern '**/*' in 'tsconfig.json'

                                            The output above show:

                                            • The initial lib.d.ts lookup based on target, and the chain of .d.ts files which are referenced
                                            • The index.ts file located via the default pattern of include

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

                                            # Diagnosa yang Diperpanjang - extendedDiagnostics

                                            Anda dapat menggunakan opsi ini untuk menemukan dimana TypeScript menghabiskan waktunya selama proses kompilasi. Peralatan ini digunakan untuk memahami karakteristik peforma basis kode Anda secara keseluruhan.

                                            Anda dapat mempelajari lebih lanjut bagaimana mengukur dan memahami hasil keluaran pada bagian wiki peforma.

                                            # Hasilkan Profil CPU - generateCpuProfile

                                            Opsi ini memberi Anda kesempatan untuk meminta TypeScript mengeluarkan profil CPU v8 selama penyusun dijalankan. Profil CPU dapat memberikan wawasan tentang mengapa proyek Anda bisa lambat.

                                            Opsi ini hanya dapat digunakan dari CLI melalui: --generateCpuProfile tsc-output.cpuprofile.

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

                                            Berkas ini dapat dibuka di peramban berbasis chromium seperti Chrome atau Edge Developer di bagian Riwayat CPU. Anda dapat mempelajari lebih lanjut tentang memahami kinerja penyusun di Bagian wiki TypeScript tentang kinerja.

                                            • Default:

                                              profile.cpuprofile

                                            • Released:

                                              3.7

                                            # List Emitted Files - listEmittedFiles

                                            Print names of generated files part of the compilation to the terminal.

                                            This flag is useful in two cases:

                                            • You want to transpile TypeScript as a part of a build chain in the terminal where the filenames are processed in the next command.
                                            • You are not sure that TypeScript has included a file you expected, as a part of debugging the file inclusion settings.

                                            For example:

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

                                            With:

                                            {
                                            "": true,
                                            }
                                            }

                                            Would echo paths like:

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

                                            Normally, TypeScript would return silently on success.

                                              # List Files - listFiles

                                              Print names of files part of the compilation. This is useful when you are not sure that TypeScript has included a file you expected.

                                              For example:

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

                                              With:

                                              {
                                              "": true
                                              }
                                              }

                                              Would echo paths like:

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

                                              Note if using TypeScript 4.2, prefer explainFiles which offers an explanation of why a file was added too.

                                              # Trace Resolution - traceResolution

                                              When you are trying to debug why a module isn’t being included. You can set traceResolution to true to have TypeScript print information about its resolution process for each processed file.

                                              #Projects

                                              # Composite - composite

                                              Opsi composite memberlakukan batasan tertentu yang memungkinkan untuk membangun (termasuk TypeScript sendiri, di bawah mode --build) untuk menentukan dengan cepat apakah proyek telah dibangun.

                                              Saat pengaturan ini aktif:

                                              • Setelan rootDir, jika tidak disetel secara eksplisit, lokasi penyimpanan akan berisi berkas tsconfig.json.

                                              • Semua berkas implementasi harus cocok dengan sebuah include contoh atau terdaftar dalam aturan files. Jika batasan ini dilanggar, tsc akan memberi tahu Anda berkas mana yang tidak ditentukan.

                                              • declaration defaults ke true

                                              Anda dapat menemukan dokumentasi tentang proyek TypeScript di the handbook.

                                              # disableReferencedProjectLoad - disableReferencedProjectLoad

                                              Dalam program TypeScript multi-proyek, TypeScript akan memuat semua proyek yang tersedia ke dalam memori untuk memberikan hasil yang akurat untuk tanggapan editor yang memerlukan grafik pengetahuan lengkap seperti ‘Temukan Semua Referensi’.

                                              Jika proyek Anda besar, Anda dapat menggunakan saran disableReferencedProjectLoad untuk menonaktifkan pemuatan otomatis semua proyek. Sebaliknya, proyek dimuat secara dinamis saat Anda membuka file melalui editor Anda.

                                              # Nonaktifkan Pencarian Solusi - disableSolutionSearching

                                              Saat bekerja dengan proyek TypeScript komposit, opsi ini menyediakan cara untuk menyatakan bahwa Anda tidak ingin proyek disertakan saat menggunakan fitur seperti find all reference atau jump to definition di editor.

                                              Saran ini untuk sesuatu yang dapat Anda gunakan untuk meningkatkan daya tanggap dalam proyek komposit besar.

                                              # Nonaktifkan Pengalihan Referensi Proyek Sumber - disableSourceOfProjectReferenceRedirect

                                              Saat bekerja dengan proyek TypeScript komposit, opsi ini menyediakan cara untuk menuju kembali ke pra-3.7 perilaku di mana berkas d.ts digunakan sebagai batas antar modul. Di 3.7, sumber kebenaran sekarang adalah berkas TypeScript Anda.

                                              # Incremental - incremental

                                              Memberi tahu TypeScript untuk menyimpan informasi tentang grafik proyek dari kompilasi terakhir ke berkas yang disimpan di penyimpanan. Ini membuat serangkaian berkas .tsbuildinfo di folder yang sama dengan keluaran kompilasi Anda. Mereka tidak menggunakan JavaScript saat runtime dan dapat dihapus dengan aman. Anda dapat membaca lebih lanjut di 3.4 release notes.

                                              Anda dapat mengontrol nama folder dengan menggunakan pilihan tsBuildInfoFile.

                                              # TS Build Info File - tsBuildInfoFile

                                              This setting lets you specify a file for storing incremental compilation information as a part of composite projects which enables faster building of larger TypeScript codebases. You can read more about composite projects in the handbook.

                                              The default depends on a combination of other settings:

                                              • If outFile is set, the default is <outFile>.tsbuildinfo.
                                              • If rootDir and outDir are set, then the file is <outDir>/<relative path to config from rootDir>/<config name>.tsbuildinfo For example, if rootDir is src, outDir is dest, and the config is ./tsconfig.json, then the default is ./tsconfig.tsbuildinfo as the relative path from src/ to ./tsconfig.json is ../.
                                              • If outDir is set, then the default is <outDir>/<config name>.tsbuildInfo
                                              • Otherwise, the default is <config name>.tsbuildInfo

                                              #Output Formatting

                                              # No Error Truncation - noErrorTruncation

                                              Do not truncate error messages.

                                              With false, the default.

                                              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

                                              With 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

                                                # Preserve Watch Output - preserveWatchOutput

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

                                                • Internal

                                                # Pretty - pretty

                                                Stylize errors and messages using color and context, this is on by default — offers you a chance to have less terse, single colored messages from the compiler.

                                                • Default:

                                                  true

                                                #Completeness

                                                # Melewati pemeriksaan pustaka bawaan - skipDefaultLibCheck

                                                Gunakan [--skipLibCheck](# skipLibCheck) sebagai gantinya. Lewati pemeriksaan jenis file deklarasi pustaka bawaan.

                                                  # Melewati pengecekan pustaka - skipLibCheck

                                                  Melewati pemeriksaan jenis berkas deklarasi.

                                                  Ini dapat menghemat waktu selama kompilasi dengan mengorbankan akurasi dari sistem type. Misalnya, dua pustaka bisa mendefinisikan dua salinan dari type (tipe) yang sama dengan cara yang tidak konsisten. Dibandingkan melakukan pengecekan menyeluruh pada semua berkas d.ts, TypeScript akan mengecek tipe data dari kode yang Anda acu secara spesifik di dalam kode sumber aplikasi.

                                                  Kasus umum dimana Anda mungkin berpikir untuk menggunakan skipLibCheck adalah ketika ada dua salinan pustaka di node_modules Anda. Dalam kasus ini, Anda harus mempertimbangkan untuk menggunakan fitur seperti yarn’s resolutions untuk memastikan hanya ada satu salinan dependency di root Anda atau menyelidiki bagaimana cara memastikan hanya ada satu resolusi dependency untuk memperbaiki masalah tanpa ada alat tambahan.

                                                  • Recommended
                                                  • Released:

                                                    2.0

                                                  #Baris Perintah

                                                  #Opsi Pengawasan

                                                  TypeScript 3.8 dilengkapi dengan strategi baru untuk mengawasi direktori, yang krusial menentukan perubahan secara efisien terhadap node_modules.

                                                  Pada sistem operasi seperti Linux, TypeScript memasang direktori pengawas (daripada pengawas berkas) pada node_modules dan banyak direktori di dalamnya untuk mendeteksi perubahan pada dependensi. Hal ini dikarenakan banyaknya pengawas berkas sering melebihi berkas-berkas yang terdapat pada node_modules, sedangkan ada lebih sedikit direktori untuk diawasi.

                                                  Karena setiap proyek mungkin bekerja dengan strategi yang berbeda, dan pendekatan baru ini mungkin tidak bekerja dengan baik dengan alur kerja anda, TypeScript 3.8 memperkenalkan opsi watchOptions yang memungkinkan pengguna untuk memberitahu kompiler/layanan bahasa strategi pengawasan yang mana yang harus digunakan untuk mengawasi berkas dan direktori.

                                                  # Menganggap Perubahan Hanya Mempengaruhi Dependensi Langsung - assumeChangesOnlyAffectDirectDependencies

                                                  Ketika opsi ini diaktifkan, TypeScript akan menghindari pemeriksaan ulang/membangun kembali semua berkas yang benar-benar mungkin terpengaruh dan hanya memeriksa ulang/membangun kembali berkas yang telah berubah serta berkas yang langsung mengimpornya.

                                                  Ini dapat dianggap sebagai implementasi ‘fast & loose’ dari algoritma pengawas, yang mana bisa secara drastis dapat mengurangi waktu rebuild dengan sesekali harus menjalankan build lengkap untuk mendapatkan semua pesan penyusun kesalahan.

                                                  # watchFile - watchFile

                                                  Strategi bagaimana setiap berkas diamati.

                                                  • fixedPollingInterval: Memeriksa setiap berkas apakah terjadi perubahan pada interval waktu tertentu.
                                                  • priorityPollingInterval: Memeriksa setiap berkas apakah terjadi perubahan, tetapi menggunakan metode heuristik untuk memeriksa tipe berkas tertentu yang jarang berubah daripada yang lain.
                                                  • dynamicPriorityPolling: Menggunakan antrian dinamis dimana berkas yang jarang diubah akan jarang diperiksa.
                                                  • useFsEvents (the default): Berusaha menggunakan even asli sistem operasi/berkas sistem untuk memeriksa perubahan berkas.
                                                  • useFsEventsOnParentDirectory: Berusaha menggunakan event asli sistem operasi/berkas sistem untuk memeriksa perubahan berkas pada direktori parent dari berkas tersebut.
                                                  • Allowed:
                                                    • fixedpollinginterval

                                                    • prioritypollinginterval

                                                    • dynamicprioritypolling

                                                    • fixedchunksizepolling

                                                    • usefsevents

                                                    • usefseventsonparentdirectory

                                                  • Released:

                                                    3.8

                                                  # watchDirectory - watchDirectory

                                                  Strategi untuk bagaimana seluruh direktori diperhatikan dalam sistem yang tidak memiliki fungsi pengawasan berkas secara rekursif.

                                                  • fixedPollingInterval: Memeriksa setiap direktori untuk memantau perubahan beberapa kali dalam satu detik secara periodik pada interval yang telah ditentukan.
                                                  • dynamicPriorityPolling: Menggunakan sebuah queue dinamis dimana direktori-direktori yang jarang mengalami modifikasi akan lebih jarang diperiksa.
                                                  • useFsEvents (the default): Mencoba menggunakan sistem operasi / kejadian asli dari sistem berkas untuk perubahan direktori.
                                                  • Allowed:
                                                    • usefsevents

                                                    • fixedpollinginterval

                                                    • dynamicprioritypolling

                                                    • fixedchunksizepolling

                                                  • Released:

                                                    3.8

                                                  # fallbackPolling - fallbackPolling

                                                  Saat menggunakan peristiwa sistem berkas, opsi ini menetapkan strategi polling yang akan digunakan saat sistem kehabisan pengamat berkas asli dan / atau tidak mendukung pengamat berkas asli.

                                                  • fixedPollingInterval: Periksa setiap berkas apakah ada perubahan beberapa kali dalam satu detik pada interval tetap.
                                                  • priorityPollingInterval: Periksa setiap berkas apakah ada perubahan beberapa kali dalam satu detik, tetapi gunakan heuristik untuk memeriksa jenis berkas tertentu lebih jarang daripada yang lain.
                                                  • dynamicPriorityPolling: Gunakan antrian dinamis di mana berkas yang lebih jarang diubah akan lebih jarang diperiksa.
                                                  • synchronousWatchDirectory: Menonaktifkan pengawas yang ditunda pada direktori. Menonton yang ditunda berguna ketika banyak perubahan berkas mungkin terjadi sekaligus (misal. Perubahan dalam node_modules dari menjalankan npm install), tetapi Anda mungkin ingin menonaktifkannya dengan tanda ini untuk beberapa penyiapan yang kurang umum.
                                                  • Allowed:
                                                    • fixedinterval

                                                    • priorityinterval

                                                    • dynamicpriority

                                                    • fixedchunksize

                                                  • Released:

                                                    3.8

                                                  # Synchronous Watch Directory - synchronousWatchDirectory

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

                                                  {
                                                  "watchOptions": {
                                                  }
                                                  }

                                                    # Exclude Directories - excludeDirectories

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

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

                                                      # Exclude Files - excludeFiles

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

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

                                                        Type Acquisition

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

                                                        # Enable - enable

                                                        Disables automatic type acquisition in JavaScript projects:

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

                                                          # Include - include

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

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

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

                                                          # Exclude - exclude

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

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

                                                          # Disable Filename Based Type Acquisition - disableFilenameBasedTypeAcquisition

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

                                                          You can disable this via disableFilenameBasedTypeAcquisition.

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