T050 Exploring Classes in TypeScript
In this assignment, you’ll delve deeper into TypeScript by working with classes. You’ll practice creating classes, defining methods, and creating instances of those classes.
Setup
- Create a new TypeScript file
Creating a Basic Class
- Create a class named
Carwith the following properties: brand: stringmodel: string-
year: number -
Add a constructor to the
Carclass that initializes the properties. -
Add a method named
displayInfoto theCarclass that prints the car’s information in the format: “Brand: [brand], Model: [model], Year: [year]”.
Instantiating the Class
- Create an instance of the
Carclass with the following details: brand: “Toyota”model: “Corolla”-
year: 2020 -
Call the
displayInfomethod on the instance to print the car’s information.
Extending the Class
- Create a new class named
ElectricCarthat extends theCarclass. - Add a new property to the
ElectricCarclass: -
batteryCapacity: number (represents the battery capacity in kWh) -
Override the
displayInfomethod in theElectricCarclass to also print the battery capacity.
Instantiating the Extended Class
- Create an instance of the
ElectricCarclass with the following details: brand: “Tesla”model: “Model 3”year: 2021-
batteryCapacity: 75 -
Call the
displayInfomethod on the instance to print the electric car’s information.
Solution
Solution
Creating a Basic Class
class Car {
brand: string;
model: string;
year: number;
constructor(brand: string, model: string, year: number) {
this.brand = brand;
this.model = model;
this.year = year;
}
displayInfo() {
console.log(`Brand: ${this.brand}, Model: ${this.model}, Year: ${this.year}`);
}
}
Instantiating the Class
Extending the Class
class ElectricCar extends Car {
batteryCapacity: number;
constructor(brand: string, model: string, year: number, batteryCapacity: number) {
super(brand, model, year);
this.batteryCapacity = batteryCapacity;
}
displayInfo() {
super.displayInfo();
console.log(`Battery Capacity: ${this.batteryCapacity} kWh`);
}
}