What is an Interface?
An interface is like a “contract” or “blueprint” that defines what properties an object must have and their types. Think of it like an architectural plan: it defines the structure before you build.Basic Syntax
Simple Example
Real-World Example: Category Interface
From our project, this interface describes the data structure the API sends for each category:main.ts
Nested Interfaces: Product
Notice how thecategory property uses the Category interface we just defined:
main.ts
Using the Product Interface
Application State Interface
Interfaces are perfect for defining your app’s state structure:main.ts
main.ts
Why Use Interfaces?
1. The Editor Warns You About Missing Properties
2. Autocompletion While Coding
3. Catch Typos Before Running
4. Self-Documenting Code
Anyone reading your code knows exactly what data structure to expect:Optional Properties
Use? to mark properties that might not always exist:
Arrays in Interfaces
Interfaces vs Types
You might also seetype used similarly:
interface is preferred. Use type for unions, primitives, and complex types.
Next Steps
- Enums - Define named constants
- Async/Await - Use interfaces with API calls
- Fetch API - Type API responses with interfaces