TypeScript offers two powerful tools for defining the shape of data: type
and interface
. But what’s the difference between them, and when should you use one over the other?
In this post, we'll cover everything you need to know about type
vs interface
, with examples, comparisons, and best practices.
🔹 What is a type
in TypeScript?
A type
is a TypeScript feature used to define aliases for primitive types, unions, intersections, tuples, and object shapes.
✅ Example:
type UserID = string | number;
type Point = {
x: number;
y: number;
};
Types are flexible and work well for complex structures like mapped types, unions, and intersections.
🔸 What is an interface
?
An interface
is typically used to define the structure of an object. It supports declaration merging and is preferred for defining public APIs or class contracts.
✅ Example:
interface Person {
name: string;
age: number;
}
You can extend interfaces to create complex structures.
interface Employee extends Person {
role: string;
}
🆚 Key Differences: type
vs interface
Feature | type |
interface |
---|---|---|
Object Shape Definition | ✅ | ✅ |
Union/Intersection Types | ✅ | ❌ |
Declaration Merging | ❌ | ✅ |
Extending Types | ✅ (via & ) |
✅ (via extends ) |
Use with Classes | ❌ | ✅ |
React Props | ✅ | ✅ (often preferred) |
🧠 When to Use type
vs interface
Here are some common guidelines:
-
Use
interface
when:- You’re defining the shape of an object or class
- You want to benefit from declaration merging
- You're working with public APIs or React props
-
Use
type
when:- You need unions or intersections
- You're defining primitive aliases or tuples
- You're working with more complex type logic
💻 Real-World Example
// Using type
type User = {
id: number;
name: string;
};
type Admin = User & {
role: 'admin';
};
// Using interface
interface IUser {
id: number;
name: string;
}
interface IAdmin extends IUser {
role: 'admin';
}
Both achieve similar results but may differ in behavior when extending or merging.
📽️ Watch the Full Video
Learn with visuals and live coding examples in this video:
🗨️ What Do You Prefer?
Do you use type
, interface
, or a mix of both in your projects? Let me know in the comments below or drop your questions!
Perfect timing for this cuz I always end up googling it again and again lol