Interface Basics
Interfaces define the structure of objects, ensuring type safety and providing clear contracts for your code.
Basic Interface
Interfaces describe the shape of an object - what properties it must have and their types:
Output
Click Run to execute your code
Best Practice: Use PascalCase for interface
names (e.g.,
Person, UserProfile).Optional Properties
Mark properties as optional with ? when they may not always be
present:
Output
Click Run to execute your code
Why Use Interfaces?
- Type Safety: Catch errors at compile time
- Documentation: Self-documenting code structure
- Autocomplete: Better IDE support
- Refactoring: Easier to change object structures
Interfaces vs Type Aliases
| Feature | Interface | Type Alias |
|---|---|---|
| Extend/Implement | ✓ Yes | ✓ Yes (with &) |
| Declaration Merging | ✓ Yes | ✗ No |
| Primitives/Unions | ✗ No | ✓ Yes |
| Best for | Object shapes | Unions, primitives |
Rule of Thumb: Use interfaces for object
shapes, type aliases for everything else.
Common Mistakes
1. Missing Required Properties
interface User {
userName: string;
email: string;
}
// ✗ Wrong - missing email
let user: User = {
userName: "alice"
};
// ✓ Correct
let user: User = {
userName: "alice",
email: "[email protected]"
};
2. Extra Properties
interface Point {
x: number;
y: number;
}
// ✗ Wrong - extra property 'z'
let point: Point = { x: 10, y: 20, z: 30 };
// ✓ Correct
let point: Point = { x: 10, y: 20 };
Summary
- Interfaces define object shapes with type safety
- Use
?for optional properties - Prefer interfaces for object types
- All required properties must be present
What's Next?
Next: Type Aliases for creating custom type names!
Enjoying these tutorials?