kodingup.camp

Beranda/TypeScript Mastery

Setup & tsconfig

Modul 2 dari 127 menit bacaSetup and tsconfig

Isi modul

    Kenapa ini penting

    Sebelum menulis tipe, kamu perlu tahu bagaimana TypeScript dipasang, dijalankan, dan dikonfigurasi. Banyak pemula frustrasi bukan karena sintaks tipe, tapi karena konfigurasi: "kenapa import saya error?", "kenapa document tidak dikenal?", "kenapa error di editor beda dengan di terminal?". Hampir semua jawabannya ada di satu file: tsconfig.json.

    Anggap tsconfig.json seperti aturan main di sebuah turnamen. Pemainnya sama (kode kamu), tapi aturan bisa ketat atau longgar: apakah boleh offside, berapa menit per babak. Kalau kamu tidak tahu aturannya, kamu akan bingung kenapa wasit meniup peluit. TypeScript 7 juga mengubah beberapa aturan default, jadi tutorial lama dari tahun 2023-2025 bisa menyesatkan.

    Konsep inti

    Instalasi

    TypeScript dipasang per proyek sebagai devDependency (hanya dipakai saat development, tidak ikut ke production):

    mkdir belajar-ts && cd belajar-ts
    npm init -y
    npm install -D typescript
    npx tsc --version
    # → Version 7.0.2
    

    Hindari npm install -g typescript untuk proyek. Versi global bisa berbeda dengan versi proyek dan membuat error "beda di laptop saya". Pakai npx tsc agar selalu memakai versi di node_modules.

    Perintah tsc yang penting

    Perintah Fungsi
    npx tsc --init Membuat tsconfig.json dengan pengaturan yang direkomendasikan
    npx tsc Memeriksa dan meng-compile proyek sesuai tsconfig.json
    npx tsc --noEmit Hanya memeriksa tipe, tidak menghasilkan file .js
    npx tsc --watch Memeriksa ulang otomatis setiap file berubah
    npx tsc -b Build proyek yang memakai project references (dipakai template Vite)
    npx tsc --showConfig Menampilkan konfigurasi hasil gabungan (termasuk extends) dan daftar file yang akan diperiksa

    Catatan TypeScript 7: kalau di folder ada tsconfig.json, menjalankan tsc nama-file.ts (menyebut file langsung) dianggap error, kecuali kamu menambahkan --ignoreConfig. Biasakan menjalankan npx tsc saja dan biarkan tsconfig.json menentukan file mana yang diperiksa.

    Isi tsconfig.json hasil tsc --init (TypeScript 7.0.2)

    Inilah yang benar-benar dihasilkan npx tsc --init (komentar dipersingkat):

    {
      "compilerOptions": {
        "module": "nodenext",
        "target": "esnext",
        "types": [],
        "sourceMap": true,
        "declaration": true,
        "declarationMap": true,
        "noUncheckedIndexedAccess": true,
        "exactOptionalPropertyTypes": true,
        "strict": true,
        "jsx": "react-jsx",
        "verbatimModuleSyntax": true,
        "isolatedModules": true,
        "noUncheckedSideEffectImports": true,
        "moduleDetection": "force",
        "skipLibCheck": true
      }
    }
    

    Penjelasan opsi yang paling sering kamu sentuh:

    Opsi Arti Catatan TS 7
    strict Menyalakan semua pemeriksaan ketat (noImplicitAny, strictNullChecks, dll.) Default true sejak TS 6.0; tetap tulis eksplisit agar jelas
    target Versi JavaScript hasil compile Default es2025; es5 sudah dihapus
    module Format modul hasil compile nodenext untuk Node, esnext/preserve untuk bundler
    moduleResolution Cara mencari file dari import Pilihan tinggal node16, nodenext, bundler; node/node10 dan classic dihapus
    lib Tipe bawaan yang tersedia (misalnya "DOM" untuk document) Untuk frontend tambahkan "DOM"
    types Paket @types/* global yang otomatis dimuat Default [] di TS 7; tulis ["node"] atau ["vite/client"] sesuai kebutuhan
    rootDir / outDir Folder sumber dan folder hasil compile rootDir default kini ./
    noEmit Hanya periksa, jangan hasilkan .js Umum di proyek Vite/Next karena bundler yang meng-compile
    jsx Cara menangani JSX react-jsx untuk React 17+
    verbatimModuleSyntax Mewajibkan import type untuk import yang hanya tipe Dibahas di modul Class & Module
    erasableSyntaxOnly Melarang sintaks TS yang menghasilkan kode runtime (enum, namespace, parameter properties) Penting kalau kode dijalankan dengan type stripping Node
    noUncheckedIndexedAccess arr[0] bertipe T \| undefined Lebih aman, sedikit lebih repot

    Apa yang berubah di TypeScript 7

    Menurut pengumuman resmi TypeScript 7.0 di devblogs.microsoft.com/typescript, perubahan default dan penghapusan yang paling terasa:

    Menjalankan TypeScript langsung di Node.js

    Node.js kini bisa menjalankan file .ts secara langsung lewat fitur type stripping: Node menghapus anotasi tipe lalu menjalankan sisanya. Statusnya menurut dokumentasi resmi Node: aktif secara default sejak v23.6.0 dan v22.18.0, dan berstatus stable sejak v25.2.0 dan v24.12.0. Di Node 26 flag --experimental-transform-types sudah dihapus.

    node --version
    # → v26.0.0
    node halo.ts
    # → Halo, Budi
    

    Batasannya penting:

    1. Node tidak memeriksa tipe. File dengan error tipe tetap dijalankan. Pemeriksaan tetap tugas tsc --noEmit.
    2. Hanya sintaks yang bisa dihapus. enum, namespace yang berisi kode, dan parameter properties di class ditolak dengan ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX. Nyalakan "erasableSyntaxOnly": true di tsconfig supaya tsc memperingatkan lebih awal.
    3. tsconfig.json diabaikan, termasuk paths.
    4. Ekstensi wajib di import: import { x } from "./util.ts", dan import yang hanya tipe wajib memakai import type.

    tsx: menjalankan TypeScript tanpa batasan sintaks

    tsx (versi 4.23.15) adalah alat populer untuk menjalankan file TypeScript di Node, termasuk enum dan fitur lain yang ditolak type stripping. Seperti Node, tsx juga tidak memeriksa tipe; ia hanya membuang tipe lalu menjalankan.

    npm install -D tsx
    npx tsx src/index.ts         # jalankan sekali
    npx tsx watch src/index.ts   # jalankan ulang setiap file berubah
    

    Pola kerja yang sehat: jalankan kode dengan node atau tsx supaya cepat, dan periksa tipe dengan tsc --noEmit (di editor, sebelum commit, dan di CI).

    Template Vite react-ts

    Untuk proyek React, kamu tidak perlu menyusun tsconfig sendiri:

    npm create vite@latest toko-ts -- --template react-ts
    cd toko-ts
    npm install
    npm run dev
    

    Template create-vite 9.3.1 menghasilkan tiga file konfigurasi: tsconfig.json (hanya berisi references), tsconfig.app.json (untuk kode di src, dengan moduleResolution: "bundler", jsx: "react-jsx", noEmit: true, erasableSyntaxOnly: true, types: ["vite/client"]), dan tsconfig.node.json (untuk vite.config.ts). Skrip build-nya "build": "tsc -b && vite build", artinya build gagal kalau ada error tipe. Vite sendiri tidak memeriksa tipe saat npm run dev; ia hanya membuang tipe supaya cepat. Error tipe kamu lihat di editor dan saat npm run build.

    Satu catatan versi: saat dicek, template tersebut masih memasang "typescript": "~6.0.3". Kalau ingin memakai TypeScript 7, jalankan npm install -D typescript@latest. Kami sudah menguji template ini dengan TypeScript 7.0.2: tsc -b dan vite build berjalan tanpa error.

    Contoh kode

    Proyek kecil Node + TypeScript dari nol:

    mkdir kalkulator-ts && cd kalkulator-ts
    npm init -y
    npm pkg set type=module
    npm install -D typescript @types/node
    npx tsc --init
    mkdir src
    

    Ubah tsconfig.json menjadi seperti ini (cukup untuk proyek Node yang dijalankan dengan type stripping):

    {
      "compilerOptions": {
        "target": "esnext",
        "module": "nodenext",
        "types": ["node"],
        "strict": true,
        "noEmit": true,
        "allowImportingTsExtensions": true,
        "erasableSyntaxOnly": true,
        "verbatimModuleSyntax": true,
        "skipLibCheck": true
      },
      "include": ["src"]
    }
    
    // src/hitung.ts
    export function tambah(a: number, b: number): number {
      return a + b;
    }
    
    export type Operasi = "tambah" | "kurang";
    
    // src/index.ts
    import { tambah } from "./hitung.ts";
    import type { Operasi } from "./hitung.ts"; // hanya tipe → wajib 'import type'
    
    const op: Operasi = "tambah";
    console.log(op, tambah(2, 3)); // → tambah 5
    
    # Periksa tipe (tidak ada output berarti aman)
    npx tsc --noEmit
    
    # Jalankan langsung dengan Node 26
    node src/index.ts
    # → tambah 5
    

    Tambahkan skrip di package.json agar timmu tidak perlu mengingat perintahnya:

    {
      "scripts": {
        "start": "node src/index.ts",
        "typecheck": "tsc --noEmit"
      }
    }
    

    Sekarang lihat bedanya "menjalankan" dan "memeriksa":

    // src/salah.ts
    const umur: number = "dua puluh"; // ❌ error TS2322: Type 'string' is not assignable to type 'number'.
    console.log(umur);
    
    node src/salah.ts
    # → dua puluh        (Node hanya membuang tipe, tidak memeriksa)
    npx tsc --noEmit
    # → src/salah.ts(2,7): error TS2322: Type 'string' is not assignable to type 'number'.
    

    Dan contoh sintaks yang ditolak type stripping:

    # src/warna.ts berisi:  enum Warna { Merah }
    node src/warna.ts
    # → SyntaxError [ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX]: TypeScript enum is not supported in strip-only mode
    npx tsx src/warna.ts
    # → 0   (tsx mendukung enum)
    

    Kesalahan umum

    1. Memasang TypeScript secara global dan lupa versi proyek. Pakai npm install -D typescript dan npx tsc supaya semua anggota tim memakai versi yang sama.
    2. Mengira npm run dev di Vite (atau node file.ts) memeriksa tipe. Keduanya hanya membuang tipe. Jalankan tsc --noEmit atau npm run build untuk memastikan tidak ada error.
    3. Menyalin tsconfig lama berisi "target": "es5", "moduleResolution": "node", atau baseUrl. Di TypeScript 7 opsi-opsi itu dihapus. Pakai bundler untuk proyek Vite/Next, nodenext untuk Node, dan paths relatif ke root proyek.
    4. Bingung Cannot find name 'process' atau describe. Sejak TS 7 types default []. Pasang @types/node (atau tipe test runner) lalu sebutkan di "types".
    5. Mematikan strict supaya error hilang. Itu membuang separuh manfaat TypeScript. Kalau migrasi terasa berat, matikan sementara per-opsi dan nyalakan kembali bertahap (lihat Proyek Akhir).

    Latihan

    1. Mudah, Buat folder baru, pasang TypeScript, jalankan npx tsc --init, lalu jalankan npx tsc --showConfig. Catat nilai strict dan target.
    2. Sedang, Buat proyek Node dengan file src/sapa.ts yang mengekspor sapa(nama: string): string, lalu src/index.ts yang memakainya. Jalankan dengan node dan periksa dengan tsc --noEmit.
    3. Menantang, Tambahkan enum Status { Aktif, Nonaktif } ke proyek latihan 2 dengan erasableSyntaxOnly: true. Amati error dari tsc, lalu ganti enum dengan union literal yang lolos type stripping.
    Lihat solusi
    # 1. Mudah
    mkdir cek-config && cd cek-config
    npm init -y && npm install -D typescript
    npx tsc --init
    npx tsc --showConfig
    # Di output terlihat "strict": true dan "target": "esnext" (diisi oleh tsc --init).
    # Tanpa menulis target sama sekali, default TS 7.0.2 adalah es2025 (lihat: npx tsc --help --all).
    
    // 2. Sedang, src/sapa.ts
    export function sapa(nama: string): string {
      return `Halo, ${nama}!`;
    }
    
    // src/index.ts
    // import { sapa } from "./sapa.ts";
    // console.log(sapa("Rina")); // → Halo, Rina!
    
    // 3. Menantang
    // enum Status { Aktif, Nonaktif }
    // error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled.
    
    // Pengganti yang "erasable": union literal + object konstan
    const STATUS = { Aktif: "aktif", Nonaktif: "nonaktif" } as const;
    type Status = (typeof STATUS)[keyof typeof STATUS]; // "aktif" | "nonaktif"
    
    function labelStatus(s: Status): string {
      return s === STATUS.Aktif ? "Sedang aktif" : "Tidak aktif";
    }
    console.log(labelStatus("aktif")); // → Sedang aktif
    

    Ringkasan

    Video pendamping

    Kalau penjelasan di atas belum masuk, tonton ini. Video dari kanal YouTube pihak lain.

    The TSConfig Cheat SheetMatt Pocock · Bahasa InggrisBuka di YouTube

    Kuis pemahaman

    Pilih satu jawaban per soal. Penjelasan muncul setelah kamu menjawab.