w3resource

TypeScript Math utility class for mathematical operations

TypeScript Classes and OOP : Exercise-22 with Solution

Write a TypeScript program that creates a class with static methods for common mathematical operations, such as add, subtract, multiply, and divide. Each method should accept two numbers as parameters and return the operation result. Test the class by performing various mathematical operations using its static methods.

Sample Solution:

TypeScript Code:

class MathUtils {
  static add(x: number, y: number): number {
    return x + y;
  }

  static subtract(x: number, y: number): number {
    return x - y;
  }

  static multiply(x: number, y: number): number {
    return x * y;
  }

  static divide(x: number, y: number): number {
    if (y === 0) {
      throw new Error("Division by zero is not allowed.");
    }
    return x / y;
  }
}

// Testing the MathUtils class
const num1 = 12;
const num2 = 5;

console.log(`Addition: ${MathUtils.add(num1, num2)}`); // Output: Addition: 17
console.log(`Subtraction: ${MathUtils.subtract(num1, num2)}`); // Output: Subtraction: 7
console.log(`Multiplication: ${MathUtils.multiply(num1, num2)}`); // Output: Multiplication: 60
console.log(`Division: ${MathUtils.divide(num1, num2)}`); // Output: Division: 2.4

Explanations:

In the exercise above -

  • First, we define a "MathUtils" class with static methods for addition, subtraction, multiplication, and division.
  • Each method takes two numbers as parameters and performs the respective mathematical operation, returning the result.
  • We test the "MathUtils" class by performing various mathematical operations using its static methods.
  • We include a check for division by zero in the "divide()" method to handle that specific case gracefully.

Output:

"Addition: 17" 
"Subtraction: 7" 
"Multiplication: 60" 
"Division: 2.4"

TypeScript Editor:

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


Previous: TypeScript counter class with static methods.
Next: TypeScript Singleton design pattern example.

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.