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"

Go to:


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

TypeScript Editor:

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


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.