1. Welcome and Icebreaker:
- If you could inherit any skill or trait from someone, what would it be?
2. Outline the Session:
- We’ll learn about inheritance in TypeScript: how classes can extend other classes and override methods.
- Learning Outcomes: Understand how to use inheritance to reuse and extend functionality.
- Let’s build on what we know!
3. Concept Explanation:
- Inheritance allows a class (child/subclass) to inherit properties and methods from another class (parent/superclass).
- Use the
extends keyword to create a subclass.
- Subclasses can override methods from the parent class.
- Use
super() to call the parent class constructor or methods.
4. Live Coding Demonstration:
class Vehicle {
make: string;
constructor(make: string) {
this.make = make;
}
drive() {
console.log(`${this.make} is driving.`);
}
}
class Car extends Vehicle {
model: string;
constructor(make: string, model: string) {
super(make);
this.model = model;
}
drive() {
console.log(`${this.make} ${this.model} is zooming!`);
}
}
const myCar = new Car("Toyota", "Corolla");
myCar.drive(); // Toyota Corolla is zooming!
5. Tasks:
- Short Exercise:
- Create a class
Employee with properties: name (string) and salary (number).
- Create a subclass
Manager that adds a property department (string) and overrides a method to print a custom message.
- Create an instance of
Manager and call its method.