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:
strictdefaulttrue,moduledefaultesnext,targetdefault versi ECMAScript stabil terbaru (di 7.0.2:es2025).typesdefault[]. Dulu semua paket@types/*dinode_modulesdimuat otomatis; sekarang harus disebut. Gejala umum:Cannot find name 'process'sampai kamu menambahkan"types": ["node"]dan memasang@types/node.- Dihapus atau jadi error:
target: "es5",downlevelIteration,moduleResolution: "node"/"classic",module: "amd"/"umd"/"system",baseUrl(pakaipathsrelatif ke root proyek),esModuleInterop: false, danalwaysStrict: false. - TypeScript 7.0 belum punya programmatic API. Alat yang memanggil API compiler (misalnya typescript-eslint) memakai paket kompatibilitas
@typescript/typescript6sampai API baru hadir di 7.1.
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:
- Node tidak memeriksa tipe. File dengan error tipe tetap dijalankan. Pemeriksaan tetap tugas
tsc --noEmit. - Hanya sintaks yang bisa dihapus.
enum,namespaceyang berisi kode, dan parameter properties di class ditolak denganERR_UNSUPPORTED_TYPESCRIPT_SYNTAX. Nyalakan"erasableSyntaxOnly": truedi tsconfig supayatscmemperingatkan lebih awal. tsconfig.jsondiabaikan, termasukpaths.- Ekstensi wajib di import:
import { x } from "./util.ts", dan import yang hanya tipe wajib memakaiimport 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
- Memasang TypeScript secara global dan lupa versi proyek. Pakai
npm install -D typescriptdannpx tscsupaya semua anggota tim memakai versi yang sama. - Mengira
npm run devdi Vite (ataunode file.ts) memeriksa tipe. Keduanya hanya membuang tipe. Jalankantsc --noEmitataunpm run builduntuk memastikan tidak ada error. - Menyalin tsconfig lama berisi
"target": "es5","moduleResolution": "node", ataubaseUrl. Di TypeScript 7 opsi-opsi itu dihapus. Pakaibundleruntuk proyek Vite/Next,nodenextuntuk Node, danpathsrelatif ke root proyek. - Bingung
Cannot find name 'process'ataudescribe. Sejak TS 7typesdefault[]. Pasang@types/node(atau tipe test runner) lalu sebutkan di"types". - Mematikan
strictsupaya error hilang. Itu membuang separuh manfaat TypeScript. Kalau migrasi terasa berat, matikan sementara per-opsi dan nyalakan kembali bertahap (lihat Proyek Akhir).
Latihan
- Mudah, Buat folder baru, pasang TypeScript, jalankan
npx tsc --init, lalu jalankannpx tsc --showConfig. Catat nilaistrictdantarget. - Sedang, Buat proyek Node dengan file
src/sapa.tsyang mengeksporsapa(nama: string): string, lalusrc/index.tsyang memakainya. Jalankan dengannodedan periksa dengantsc --noEmit. - Menantang, Tambahkan
enum Status { Aktif, Nonaktif }ke proyek latihan 2 denganerasableSyntaxOnly: true. Amati error daritsc, 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
- Pasang per proyek:
npm install -D typescript, jalankan dengannpx tsc; versi saat ini 7.0.2. tsc --noEmitmemeriksa tipe tanpa menghasilkan file;node file.ts,tsx, dan Vite hanya membuang tipe tanpa memeriksa.- Di TS 7:
strictdefaulttrue,typesdefault[], danes5,moduleResolution: "node", sertabaseUrldihapus. - Node.js menjalankan
.tslewat type stripping (stable sejak v25.2/v24.12), tanpaenum/namespace/parameter properties dan wajib ekstensi.ts. - Untuk React, mulai dari
npm create vite@latest -- --template react-ts, lalunpm install -D typescript@latestjika ingin TS 7.