🚀 Type vs Interface in TypeScript – with Practical Examples If you’re learning TypeScript, understanding type and interface is a must. Both are used to define the shape of an object, but they have some differences. 🔹 Using interface Best when you’re defining object structures and planning to extend them. interface User { readonly id: number; // cannot be changed name: string; email?: string; // optional property isActive: boolean; greet(): string; // method inside interface } const user: User = { id: 1, name: "Avishkar", isActive: true, greet() { return `Hello, ${this.name}`; } }; // user.id = 2 ❌ Error: Cannot assign to 'id' because it is read-only 🔹 Using type More flexible. You can use it with unions, intersections, and primitives. type Admin = { readonly adminId: number; // read-only role?: string; // optional permissions: string[]; getRole(): string; // method inside type }; const admin: Admin = { adminId: 101, permissions: ["read", "write"], getRole() { return this.role ?? "Super Admin"; } }; 🔹 Key Differences (Quick View) ✅ interface → extendable, preferred for objects & APIs ✅ type → more powerful (unions, intersections) 🔒 readonly → value cannot be reassigned ❓ ? → makes a property optional TypeScript makes your code safer, cleaner, and more predictable 🔥 #TypeScript #FrontendDevelopment #JavaScript #WebDevelopment #ReactJS #LearningInPublic
type aliases are also extendable (building intersection types with & is essentially the same as extending interfaces). So it's not a real difference. Also, both type aliases and interfaces are fubctionally equally good for objects and dto's, it'slargely just a matter of preference
Does anyone know the difference between ?? and || in JavaScript or TypeScript?