Recraftory

TypeScript - Interface dan Type

TypeScript menyediakan dua cara untuk mendefinisikan bentuk data: interface dan type.

Interface

Interface digunakan untuk mendefinisikan kontrak bentuk objek.

interface Pengguna {
  id: number;
  nama: string;
  email?: string;      // opsional
  readonly dibuatPada: Date; // tidak bisa diubah setelah inisialisasi
}

let user: Pengguna = {
  id: 1,
  nama: "Alice",
  dibuatPada: new Date(),
};

// user.dibuatPada = new Date(); // ❌ Error: readonly property

Extending Interface

interface Hewan {
  nama: string;
  umur: number;
}

interface Kucing extends Hewan {
  jenis: string;
  bisaMenyusul: boolean;
}

let kucing: Kucing = {
  nama: "Milo",
  umur: 2,
  jenis: "Persia",
  bisaMenyusul: true,
};

Interface Declaration Merging

interface Mobil {
  merk: string;
}

interface Mobil {
  model: string;
}

// Mobil sekarang memiliki merk dan model
let mobil: Mobil = { merk: "Toyota", model: "Camry" };

Type Alias

Type alias lebih fleksibel dan mendukung union, intersection, dan tipe kompleks.

type ID = string | number;
type Koordinat = [number, number];

type Status = "aktif" | "nonaktif" | "ditangguhkan";

let status: Status = "aktif";
// status = "lain"; // ❌ Error

Intersection dengan Type

type Admin = Pengguna & {
  role: "admin";
  permissions: string[];
};

Interface vs Type — Kapan Menggunakan?

FiturInterfaceType
Extends / implements✅ Lebih baik✅ Bisa, tapi kurang ideal
Declaration merging
Union types
Tuple / primitive
Mapped types

Rekomendasi

  • Gunakan interface untuk bentuk objek yang mungkin perlu di-extend
  • Gunakan type untuk union, tuple, atau tipe kompleks