0
0
Typescriptprogramming~20 mins

Why modules are needed in TypeScript - See It in Action

Choose your learning style9 modes available
Why modules are needed in TypeScript
📖 Scenario: Imagine you are building a small library of math functions. You want to keep your code organized and avoid mixing everything in one file. Modules help you split your code into parts that can be used separately and safely.
🎯 Goal: You will create two TypeScript files: one module that exports a function, and another file that imports and uses that function. This shows why modules are needed to organize and reuse code.
📋 What You'll Learn
Create a module file that exports a function
Create a main file that imports the function from the module
Use the imported function to calculate and display a result
💡 Why This Matters
🌍 Real World
In real projects, modules help keep code organized and manageable as projects grow.
💼 Career
Understanding modules is essential for working on professional TypeScript or JavaScript projects where code reuse and organization matter.
Progress0 / 4 steps
1
Create a module file with a function
Create a file named mathUtils.ts and write a function called add that takes two numbers a and b and returns their sum. Export this function using export.
Typescript
Need a hint?

Use export function add(a: number, b: number): number { return a + b; } to create and export the function.

2
Create a main file to import the function
Create a file named main.ts. Import the add function from ./mathUtils using import { add } from './mathUtils';.
Typescript
Need a hint?

Use import { add } from './mathUtils'; to bring the function into main.ts.

3
Use the imported function to calculate a sum
In main.ts, call the add function with arguments 5 and 7 and store the result in a variable called result.
Typescript
Need a hint?

Write const result = add(5, 7); to call the function and save the sum.

4
Print the result to the console
In main.ts, write a console.log statement to display the value of result.
Typescript
Need a hint?

Use console.log(result); to show the sum in the console.