TypeScript Basic Namespace
TypeScript Modules and Namespaces : Exercise-6 with Solution
Write a TypeScript namespace called MathUtility that contains functions for basic mathematical operations such as addition, subtraction, multiplication, and division. Write the functions inside the namespace and use them to perform operations.
Sample Solution:
TypeScript Code:
main.ts
import MathUtility from './MathUtility';
const num1 = 12;
const num2 = 7;
const sum = MathUtility.add(num1, num2);
console.log(`Sum: ${sum}`); // Output: Sum: 19
const difference = MathUtility.subtract(num1, num2);
console.log(`Difference: ${difference}`); // Output: Difference: 5
const product = MathUtility.multiply(num1, num2);
console.log(`Product: ${product}`); // Output: Product: 84
const quotient = MathUtility.divide(num1, num2);
console.log(`Quotient: ${quotient}`); // Output: Quotient: 1.7142857142857142
MathUtility.ts
namespace MathUtility {
export function add(x: number, y: number): number {
return x + y;
}
export function subtract(x: number, y: number): number {
return x - y;
}
export function multiply(x: number, y: number): number {
return x * y;
}
export function divide(x: number, y: number): number {
if (y === 0) {
throw new Error("Division by zero is not allowed.");
}
return x / y;
}
}
export default MathUtility;
Explanation:
In the exercise above -
- MathUtility.ts is a TypeScript namespace that contains functions for addition, subtraction, multiplication, and division. These functions are exported from the namespace.
- In main.ts, we import the "MathUtility" namespace using the import statement.
- Next we use the functions from the "MathUtility" namespace to perform addition, subtraction, multiplication, and division operations on 'num1' and 'num2'.
- The imported namespace provides a way to encapsulate and organize related functions while making them available for use in other parts of your code.
Output:
Sum: 19 Difference: 5 Product: 84 Quotient: 1.7142857142857142
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript Circular Dependencies.
Next: TypeScript Nested Namespaces.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://w3resource.com/typescript-exercises/typescript-modules-and-namespaces-exercise-6.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics