Hari 11: Class dengan TypeScript
65 min
Last updated 09 Apr 2026
Class di TypeScript
class Produk {
readonly id: number;
private _stok: number;
constructor(
id: number,
public nama: string, // shorthand property declaration
public harga: number,
stok: number = 0,
) {
this.id = id;
this._stok = stok;
}
get stok(): number { return this._stok; }
set stok(nilai: number) {
if (nilai < 0) throw new RangeError("Stok tidak boleh negatif");
this._stok = nilai;
}
tampilkan(): string {
return `[${this.id}] ${this.nama} - Rp ${this.harga.toLocaleString()} (stok: ${this._stok})`;
}
}
const laptop = new Produk(1, "Laptop", 8500000, 10);
laptop.stok = 15;
console.log(laptop.tampilkan());
Abstract Class
abstract class Bentuk {
abstract luas(): number;
abstract keliling(): number;
deskripsi(): string {
return `Luas: ${this.luas().toFixed(2)}, Keliling: ${this.keliling().toFixed(2)}`;
}
}
class Lingkaran extends Bentuk {
constructor(private r: number) { super(); }
luas(): number { return Math.PI * this.r ** 2; }
keliling(): number { return 2 * Math.PI * this.r; }
}
const c = new Lingkaran(7);
console.log(c.deskripsi()); // Luas: 153.94, Keliling: 43.98
💡
Notice: Abstract class tidak bisa diinstansiasi langsung. Semua method/property abstract wajib diimplementasikan di class turunan.
Assignment
Buat abstract class Kendaraan dengan abstract property kecepatan: number, abstract method info(): string, dan method nonAbstrak isCepat(): boolean (kecepatan > 100). Buat class Motor dan Mobil yang extend Kendaraan.
Expected output:
Motor (120 km/h) — Cepat
Mobil Toyota (180 km/h) — Cepat
TS
index.ts
Solution
Output