TypeScript - Basic class definition
TypeScript Classes and OOP : Exercise-1 with Solution
Write a TypeScript class called Bus with the properties make, model, and year. Implement a constructor that initializes these properties when a Bus object is created.
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;
}
}
// Create a Bus object
const myBus = new Bus("Volvo", "9400 B11R", 2019);
// Access and print the properties
console.log("Make:", myBus.make); // Output: Make: Volvo
console.log("Model:", myBus.model); // Output: Model: 9400 B11Rr
console.log("Year:", myBus.year);
Explanations:
In the exercise above -
- First, we define the "Bus" class with properties 'make', 'model', and 'year'.
- The constructor for the "Bus" class takes three parameters: 'make', 'model', and 'year'. Inside the constructor, we initialize the properties using the provided values.
- We create an instance of the "Bus" class called 'myBus' by calling the constructor with specific values.
- Finally, we access and print the properties of the 'myBus' object to verify that they have been initialized correctly.
Output:
"Make:" "Volvo" "Model:" "9400 B11R" "Year:" 2019
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript Classes and OOP Exercises Home
Next: TypeScript Class with Methods.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/typescript-exercises/typescript-class-and-oop-exercise-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics