w3resource

TypeScript Basic Constructor

TypeScript Classes and OOP : Exercise-5 with Solution

Write a TypeScript program that creates a class called Student with properties name and class. Implement a constructor that initializes these properties when a Student object is created.

Sample Solution:

TypeScript Code:

class Student {
  // Properties
  name: string;
  className: string;

  // Constructor
  constructor(name: string, className: string) {
    this.name = name;
    this.className = className;
  }
}

// Create a Student object
const myStudent = new Student("Tashina Cihangir", "Class V");

// Access and print the properties
console.log("Name:", myStudent.name);         // Output: Name: Tashina Cihangir
console.log("Class Name:", myStudent.className); // Output: Class Name: Class V

Explanations:

In the exercise above -

  • First, we define the "Student" class with properties 'name' and 'className'.
  • The constructor for the "Student" class takes two parameters: 'name' and 'className'. Inside the constructor, we initialize the properties using the provided values.
  • Next, we create an instance of the "Student" class called 'myStudent' by calling the constructor with specific values.
  • Finally, we access and print the properties of the 'myStudent' object to verify that they have been initialized correctly.

Output:

"Name:" "Tashina Cihangir"
"Class Name:" "Class V"

TypeScript Editor:

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


Previous: TypeScript Class Composition.
Next: TypeScript Constructor Overloading.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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-5.php