Interfaces define the shape of your data. They’re like blueprints that describe what properties an object should have and what types those properties should be.
Why use interfaces?
- Documentation - They clearly show what data your functions expect
- Type checking - TypeScript ensures objects match the interface
- Autocomplete - Your editor knows what properties are available
- API contracts - They define the structure of data sent between frontend and backend
Common use cases:
- API request/response data
- Database records
- Configuration objects
- Function parameters
interface User {
id: number;
name: string;
email: string;
createdAt: Date;
}
interface Product {
id: number;
name: string;
price: number;
inStock: boolean;
}
// Using interfaces
const user: User = {
id: 1,
name: "Sarah Chen",
email: "sarah@example.com",
createdAt: new Date(),
};
// TypeScript will error if you miss a property or use wrong types
const badUser: User = {
id: "1", // ❌ Error! Should be number
name: "Sarah", // ✅ Correct
// ❌ Error! Missing email and createdAt
};
Optional Properties:
Sometimes properties might not always be present. Use ? to make them optional:
interface UserProfile {
id: number;
name: string;
email: string;
avatarUrl?: string; // Optional - user might not have an avatar
bio?: string; // Optional - user might not have a bio
phoneNumber?: string; // Optional - user might not provide phone
}
const user1: UserProfile = {
id: 1,
name: "Sarah",
email: "sarah@example.com",
// avatarUrl, bio, and phoneNumber are optional, so we can omit them
};