w3resource

TypeScript Constructor Initialization

TypeScript Classes and OOP : Exercise-8 with Solution

Write a TypeScript class called Student with properties name and age. Implement a constructor that initializes these properties when a Student object is created. Additionally, add validation to ensure that the age provided is a positive number. If the age is not positive, set it to a default value of 0.

Sample Solution:

TypeScript Code:

class Student {
  // Properties
  name: string;
  age: number;

  // Constructor with validation
  constructor(name: string, age: number) {
    this.name = name;

    // Validate and set the age property
    if (age > 0) {
      this.age = age;
    } else {
      // Default to 0 if age is not positive
      this.age = 0;
    }
  }
}

// Create Student objects with different ages
const student1 = new Student("Erland Clive", 22);    // Age is positive
const student2 = new Student("Bastet Aneta", -7);  // Age is not positive

// Access and print the properties
console.log("Student 1 - Name:", student1.name, "Age:", student1.age); // Output: Student 1 - Name: Erland Clive Age: 22
console.log("Student 2 - Name:", student2.name, "Age:", student2.age); // Output: Student 2 - Name: Bastet Aneta Age: 0 (default)

Explanations:

In the exercise above -

  • First we define the "Student" class with properties 'name' and 'age'.
  • The constructor for the "Student" class takes two parameters: 'name' and 'age'. Inside the constructor, we set the 'name' property to the provided name.
  • Include validation to ensure that the 'age' provided is a positive number. If the 'age' is greater than 0, we set the 'age' property to that value. Otherwise, we default the 'age' property to 0.
  • Next, we create two "Student" objects with different ages, including one with a negative age to demonstrate validation and default value assignment.
  • Finally, we access and print the properties of both 'Student' objects to verify that they have been initialized correctly. The validation and default assignment work as expected.

Output:

"Student 1 - Name:" "Erland Clive" "Age:" 22
"Student 2 - Name:" "Bastet Aneta" "Age:" 0

TypeScript Editor:

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


Previous: TypeScript Derived Class Constructor.
Next: TypeScript Basic Inheritance.

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