TypeScript is a statically-typed superset of JavaScript that provides more advanced features like classes, interfaces, and modules. In this tutorial, we will focus on modules in TypeScript.
What are Modules?
A module is a self-contained unit of code that encapsulates related code and data. It allows you to organize your code into logical units, making it more modular and reusable. Modules in TypeScript are similar to modules in other programming languages like Python and Java.
Exporting and Importing Modules
To export a module in TypeScript, you use the export keyword before the module definition. For example, let's say we have a file called math.ts that contains a function called add:
export function add(a: number, b: number): number {
return a + b;
}To use this function in another file, we use the import keyword. For example, let's say we have a file called app.ts that needs to use the add function from math.ts:
import { add } from './math';
console.log(add(1, 2)); // Output: 3In the above code, we use the import keyword to import the add function from the math.ts module. We then use the console.log function to output the result of calling the add function with arguments 1 and 2.
Default Exports
In addition to named exports, TypeScript also supports default exports. A default export is a single export that is the "default" export of the module. You can have at most one default export per module. Here's an example:
export default function add(a: number, b: number): number {
return a + b;
}To import a default export, you can use any name you like. For example:
import sum from './math';
console.log(sum(1, 2)); // Output: 3In the above code, we import the default export from math.ts using the name sum.
Re-exporting Modules
You can also re-export a module in TypeScript. Re-exporting allows you to export modules from other modules without having to modify the original module. Here's an example:
export * from './math';In the above code, we use the export * syntax to re-export all the named exports from the math.ts module. We can then import these exports in another file like this:
import { add } from './math';Conclusion
In this tutorial, we've covered the basics of modules in TypeScript. We've seen how to export and import modules, use default exports, and re-export modules. Modules are an important feature of TypeScript that can help you write more modular and reusable code.