TypeScript Exporting Functions
TypeScript Modules and Namespaces : Exercise-1 with Solution
Write a TypeScript module that exports two functions, add and subtract. Add should accept two numbers and return their sum, while subtract should accept two numbers and return their difference. Import and use these functions in a separate TypeScript file to perform addition and subtraction operations.
Sample Solution:
TypeScript Code:
main.ts
import { add, subtract } from './math_utils';
const num1 = 100;
const num2 = 500;
const sum = add(num1, num2);
console.log(`Sum: ${sum}`); // Output: Sum: 600
const difference = subtract(num1, num2);
console.log(`Difference: ${difference}`); // Output: Difference: 400
math_utils.ts
export function add(x: number, y: number): number {
return x + y;
}
export function subtract(x: number, y: number): number {
return x - y;
}
Explanations:
In the exercise above -
- "math_utils.ts" is a TypeScript module that exports the 'add' and 'subtract' functions.
- In "main.ts", we import the "add()" and "subtract()" functions from the 'mathOperations' module.
- We then use these imported functions to perform addition and subtraction operations on 'num1' and 'num2'.
- Finally when we run "main.ts", it will perform the operations and display the results.
Output:
Sum: 600 Difference: -400
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript Modules and Namespaces Exercises Home
Next: TypeScript Exporting Classes.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics