TypeScript Interface vs Type: Contracts & Object Structure

TypeScript Type vs Interface Use interface → For Contracts & Object Structure ✅ Service contracts ✅ Domain models ✅ DTOs ✅ Class implementations export interface PaymentProvider { charge(amount: number): Promise<boolean> refund(id: string): Promise<boolean> } class StripeProvider implements PaymentProvider {} interface User { id: string email: string } 𝗜𝗡𝗧𝗘𝗥𝗙𝗔𝗖𝗘: Use when defining object shape or implementation contract. Use type → For Unions, States & Advanced Types ✅ Union types ✅ Event models ✅ API response wrappers ✅ Utility & composition types type UserRole = "ADMIN" | "USER" | "SUPPORT" type ApiResponse<T> = | { success: true; data: T } | { success: false; error: string } type AdminUser = User & { permissions: string[] } 𝗧𝗬𝗣𝗘: Use when modeling states, variations, or type logic. 🎯 Simple Rule Contract or extendable object → interface Union or advanced typing → type #TypeScript #JavaScript #BackendDevelopment #WebDevelopment #SoftwareArchitecture #CleanCode #NestJS #NodeJS #Programming

  • No alternative text description for this image

But this actually is not a fixed rule or something nah? I think it actually varies from team to team. Like where I'm now they use interface when they're making a custom library which will be used later on different applications. But for an application they often strict to just types. However, yeah both type and interface has some limitations.

Like
Reply

To view or add a comment, sign in

Explore content categories