TypeScript - Pengenalan
TypeScript adalah superset JavaScript yang menambahkan sistem tipe statis. Kode TypeScript dikompilasi menjadi JavaScript biasa sebelum dijalankan di browser atau Node.js.
Mengapa TypeScript?
- Deteksi error lebih awal — kesalahan tipe tertangkap saat compile time, bukan runtime
- Autocompletion dan IntelliSense — IDE dapat memberikan saran yang lebih akurat
- Dokumentasi yang hidup — tipe berfungsi sebagai dokumentasi kode
- Refactoring lebih aman — perubahan besar dapat dilakukan dengan confidence
- Kompatibel dengan JavaScript — semua kode JS valid di TS
Instalasi
npm install typescript --save-dev
npx tsc --initFile tsconfig.json mengatur konfigurasi kompilasi.
Konfigurasi Dasar tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"outDir": "./dist"
},
"include": ["src/**/*"]
}Kompilasi
# Kompilasi semua file
npx tsc
# Watch mode (kompilasi otomatis saat file berubah)
npx tsc --watchPerbedaan dengan JavaScript
// JavaScript
function jumlah(a, b) {
return a + b;
}
// TypeScript — parameter dan return value punya tipe
function jumlah(a: number, b: number): number {
return a + b;
}
// Error terdeteksi saat compile
jumlah("1", "2"); // ❌ Argument of type 'string' is not assignable to parameter of type 'number'