Types & Interfaces
15 min
Last updated 23 Mar 2026
Types & Interfaces di TypeScript
TypeScript menyediakan dua cara untuk mendefinisikan bentuk sebuah objek: Type Alias dan Interface. Keduanya mirip, tapi ada perbedaan penting.
Type Alias
type User = {
id: number;
name: string;
email: string;
role: "admin" | "user" | "guest"; // Union type
};
const user: User = {
id: 1,
name: "Khansa",
email: "khansa@email.com",
role: "admin",
};
Interface
interface Product {
id: number;
name: string;
price: number;
description?: string; // Optional property
}
const laptop: Product = {
id: 42,
name: "MacBook Air",
price: 15000000,
// description boleh tidak diisi karena optional
};
Perbedaan Type vs Interface
- Interface bisa di-extend dan di-merge — cocok untuk kontrak objek dan class
- Type lebih fleksibel — bisa untuk union types, intersection types, dan primitive types
- Untuk objek biasa, keduanya hampir identik
// Extend Interface
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
// Intersection Type
type AdminUser = User & { permissions: string[] };
Konvensi umum: Gunakan interface untuk mendefinisikan "bentuk" objek dan class. Gunakan type untuk union types dan tipe yang lebih kompleks.