w3resource

TypeScript counter class with static methods

TypeScript Classes and OOP : Exercise-21 with Solution

Write a TypeScript class called Counter with a static property count initialized to 0. Implement a static method increment() that increments the count by 1. Implement another static method getCount() that returns the current count value. Test the class by calling both methods.

Sample Solution:

TypeScript Code:

class Counter {
  private static count: number = 0;

  static increment(): void {
    Counter.count++;
  }

  static getCount(): number {
    return Counter.count;
  }
}

// Testing the Counter class
Counter.increment();
Counter.increment();
Counter.increment();
Counter.increment();

console.log(`Current count: ${Counter.getCount()}`); // Output: Current count: 4

Explanations:

In the exercise above -

  • First, define a "Counter" class with a private static property 'count' initialized to 0.
  • Implement a static method "increment()" that increments the 'count' by 1 each time it is called.
  • Implement another static method "getCount()" that returns the current value of 'count'.
  • Finally, test the "Counter" class by calling the "increment()" method three times and then displaying the current count using the "getCount()" method. The output should indicate a count of 4.

Output:

"Current count: 4"

TypeScript Editor:

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


Previous: TypeScript Animal Class with Protected and Private Properties.
Next: TypeScript Math utility class for mathematical operations.

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