1. Welcome and Icebreaker:
- If you could design a class to represent any real-world object, what would it be and what properties would it have?
2. Outline the Session:
- We’ll learn about classes in TypeScript: how to define them, add properties and methods, and use constructors.
- Learning Outcomes: Understand how to create and use classes as blueprints for objects.
- Let’s get object-oriented!
3. Concept Explanation:
- Classes are blueprints for creating objects with specific properties and methods.
- In TypeScript, classes can have typed properties, methods, and constructors.
- Syntax:
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
- Classes can also have access modifiers (
public, private, protected) and can implement interfaces.
4. Live Coding Demonstration:
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
const dog = new Animal("Buddy");
dog.speak(); // Buddy makes a sound.
class Dog extends Animal {
breed: string;
constructor(name: string, breed: string) {
super(name);
this.breed = breed;
}
speak() {
console.log(`${this.name} barks!`);
}
}
const beagle = new Dog("Max", "Beagle");
beagle.speak(); // Max barks!
5. Tasks:
- Short Exercise:
- Create a class
Book with properties: title (string), author (string), and year (number).
- Add a method
getSummary that returns a string summary of the book.
- Create an instance of
Book and print its summary.
- Extend
Book with a subclass EBook that adds a fileSize property (number, in MB) and overrides getSummary to include the file size.