#typescript
#oop
#interfaces
Day 12: Implementing Interfaces in Classes
The Contract
Welcome to Day 12! This is the final day of Phase 2. We’ve seen Interfaces for objects, and Classes for logic. Now let’s combine them.
implements
You can enforce that a Class meets a specific contract (Interface) using the implements keyword.
interface ClockInterface {
currentTime: Date;
setTime(d: Date): void;
}
class Clock implements ClockInterface {
currentTime: Date = new Date(); // Must be public
setTime(d: Date) {
this.currentTime = d;
}
constructor(h: number, m: number) { }
}
If you fail to implement a property or method from the interface, TypeScript will show an error.
Interface for Public Side Only
Remember, an interface only describes the public side of the class. You cannot use it to check for private properties.
Multiple Interfaces
A class can implement multiple interfaces.
class SmartPhone implements Phone, Computer, Camera {
// ... needs to implement everything from all 3
}
Phase 2 Wrap-Up
Congratulations! You’ve mastered Object-Oriented TypeScript. You now know:
- Classes and Instances.
- Public, Private, Protected modifiers.
- Inheritance and Abstract Classes.
- Statics, Getters, and Setters.
- Using Interfaces with Classes.
Coming up in Phase 3 (Day 13-18): Advanced Types (Unions, Generics, Type Guards). This is where TypeScript gets really powerful.
Challenge for Today
- Define an interface
Playablewith a methodplay(). - Define an interface
Recordablewith a methodrecord(). - Create a class
MediaPlayerthat implements both. - Try to remove one of the methods and observe the error.
See you in Phase 3!