Skip to content

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

  1. Create a new TypeScript file

Creating a Basic Class

  1. Create a class named Car with the following properties:
  2. brand: string
  3. model: string
  4. year: number

  5. Add a constructor to the Car class that initializes the properties.

  6. Add a method named displayInfo to the Car class that prints the car’s information in the format: “Brand: [brand], Model: [model], Year: [year]”.

Instantiating the Class

  1. Create an instance of the Car class with the following details:
  2. brand: “Toyota”
  3. model: “Corolla”
  4. year: 2020

  5. Call the displayInfo method on the instance to print the car’s information.

Extending the Class

  1. Create a new class named ElectricCar that extends the Car class.
  2. Add a new property to the ElectricCar class:
  3. batteryCapacity: number (represents the battery capacity in kWh)

  4. Override the displayInfo method in the ElectricCar class to also print the battery capacity.

Instantiating the Extended Class

  1. Create an instance of the ElectricCar class with the following details:
  2. brand: “Tesla”
  3. model: “Model 3”
  4. year: 2021
  5. batteryCapacity: 75

  6. Call the displayInfo method 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

let myCar = new Car("Toyota", "Corolla", 2020);
myCar.displayInfo();

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`);
    }
}

Instantiating the Extended Class

let myElectricCar = new ElectricCar("Tesla", "Model 3", 2021, 75);
myElectricCar.displayInfo();