Interfaces
Define contracts for object shapes using interfaces in TypeScript.
Interfaces
Interfaces define a contract — the shape an object must follow.
Defining an Interface
interface IsPerson {
name: string;
age: number;
speak(text: string): void;
spend(amount: number): number;
}
Using Interfaces
const me: IsPerson = {
name: "Mario",
age: 30,
speak(text: string): void {
console.log(text);
},
spend(amount: number): number {
console.log("I spent", amount);
return amount;
},
};
const greetPerson = (person: IsPerson) => {
console.log("Hello", person.name);
};
Interface vs Type Alias
| Feature | Interface | Type Alias |
|---|---|---|
| Object shapes | ✅ | ✅ |
| Extends/implements | ✅ | Via intersection |
| Declaration merging | ✅ | ❌ |
| Union types | ❌ | ✅ |
Key Takeaways
- Interfaces define contracts for object shapes
- Objects must have all properties defined in the interface
- Use interfaces for objects, type aliases for unions/primitives