TypeScript Interfaces
🧩 TypeScript Interfaces
It tells TypeScript what properties and methods an object must have.
Interfaces are especially powerful for object-oriented design, APIs, and large projects.
1️⃣ Basic Interface
✔ All properties are required
❌ Missing or extra properties cause an error
2️⃣ Optional Properties (?)
3️⃣ Readonly Properties
Once set, cannot be changed.
4️⃣ Interface with Methods
5️⃣ Interface for Function Types
6️⃣ Interface with Arrays
7️⃣ Extending Interfaces
One interface can inherit another.
8️⃣ Interface Declaration Merging ⭐
Interfaces can be merged automatically.
⚠️ This is not possible with type aliases.
9️⃣ Interface vs Type Alias
| Feature | Interface | Type |
|---|---|---|
| Object Shape | ✅ Yes | ✅ Yes |
| Declaration Merging | ✅ Yes | ❌ No |
| Extending | extends |
& |
| Union Types | ❌ No | ✅ Yes |
| Best For | Objects & classes | Complex types |
📌 Rule of Thumb
-
Use interface for object structures & public APIs
-
Use type for unions, primitives, functions
🔑 Interfaces Summary
| Feature | Example |
|---|---|
| Basic | interface A {} |
| Optional | prop?: type |
| Readonly | readonly prop |
| Methods | method(): void |
| Extend | interface B extends A |
| Merge | Same name interfaces |
⭐ Best Practices
✔ Use interfaces for object contracts
✔ Prefer interfaces with classes & APIs
✔ Use readonly for immutability
✔ Keep interfaces small and focused
