1. Welcome and Icebreaker:
- If you could define a contract for your ideal job, what would be required and what would be optional?
2. Outline the Session:
- We’ll learn about interfaces in TypeScript: how to define contracts for classes and objects.
- Learning Outcomes: Understand how interfaces enforce structure and how to implement them.
- Let’s get structured!
3. Concept Explanation:
- Interfaces define the shape of objects and contracts for classes.
- Classes and objects that implement an interface must have all its properties and methods.
- Interfaces can extend other interfaces.
- Use
implements to make a class follow an interface.
4. Live Coding Demonstration:
interface Logger {
log(message: string): void;
}
class ConsoleLogger implements Logger {
log(message: string): void {
console.log(`LOG: ${message}`);
}
}
const logger = new ConsoleLogger();
logger.log("Hello, interface!");
// Interface for objects
interface Point {
x: number;
y: number;
}
const pt: Point = { x: 10, y: 20 };
console.log(pt);
5. Tasks:
- Short Exercise:
- Define an interface
Vehicle with properties: make (string), model (string), and a method drive().
- Create a class
Truck that implements Vehicle.
- Create an instance of
Truck and call its drive() method.