w3resource

TypeScript Class with Methods

TypeScript Classes and OOP : Exercise-2 with Solution

Write a TypeScript class called Bus with the properties make, model, and year. Add a method start() that prints a message indicating that the Bus is starting.

Sample Solution:

TypeScript Code:

class Bus {
  // Properties
  make: string;
  model: string;
  year: number;

  // Constructor
  constructor(make: string, model: string, year: number) {
    this.make = make;
    this.model = model;
    this.year = year;
  }

  // Method to start the bus
  start() {
    console.log(`The ${this.make} ${this.model} (Year: ${this.year}) is starting.`);
  }
}

// Create a Bus object
const myBus = new Bus("Volvo", "9400 B11R", 2019);

// Call the start method to start the bus
myBus.start(); 

Explanations:

In the exercise above -

  • First, we define the "Bus" class with properties 'make', 'model', and 'year', just like in the previous example.
  • Add a "start()" method to the "Bus" class. Inside the "start()" method, we use console.log() to print a message indicating that the bus is starting, including its make, model, and year.
  • Create an instance of the "Bus" class called 'myBus' using the constructor with specific values.
  • Finally, we call the "start()" method on the 'myBus' object to initiate the bus and print the starting message.

Output:

"The Volvo 9400 B11R (Year: 2019) is starting."

TypeScript Editor:

See the Pen TypeScript by w3resource (@w3resource) on CodePen.


Previous: TypeScript - Basic class definition.
Next: TypeScript Class Inheritance.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.