
Play Store Application link β Java to TypeScript in 14 Steps – App on Google Play
Step 12 – Introduction to Modules in TypeScript
Modules in TypeScript help you organize and manage code by breaking it into reusable pieces that can be imported and used across your application. Think of modules as separate files or collections of files that group related functionalities together, making your code more maintainable and modular.
Creating a Module in TypeScript
To create a module, you use the export
keyword to expose functions, classes, or variables from a file so they can be imported elsewhere.
Java Comparison:
In Java, this is similar to using packages and public
access modifiers to make classes or methods accessible from other packages.
TypeScript Example:
Create a file named greeting.ts
:
// greeting.ts
export function sayHello(name: string) {
console.log(`Hello, ${name}!`);
}
In this example, the sayHello
function is exported from the greeting.ts
module and can be used in other files.
Importing a Module in TypeScript
To use something exported from a module, you import it using the import
keyword.
Java Comparison:
In Java, this is similar to using import
statements to bring in classes from other packages.
TypeScript Example:
Create a file named main.ts
:
// main.ts
import { sayHello } from "./greeting";
sayHello("John");
Here, we import the sayHello
function from greeting.ts
and use it in the main.ts
file.
Default Exports in TypeScript Modules
TypeScript also supports default exports. A default export allows you to export a single value from a module and import it without using braces.
Java Comparison:
In Java, a similar concept would be a class with a single entry point or an instance that you can use directly.
TypeScript Example:
Update greeting.ts
to use a default export:
// greeting.ts
export default function sayHello(name: string) {
console.log(`Hello, ${name}!`);
}
TypeScript Example for Importing Default Export:
In main.ts
, you can import the default export without braces:
// main.ts
import myGreeting from "./greeting";
myGreeting("John");
In this case, the default export from greeting.ts
can be imported with any name you choose (in this case, myGreeting
).
Conclusion
Modules in TypeScript are essential for organizing and structuring your code. They let you split your code into manageable pieces, making it more maintainable and reusable. By using export
and import
, you can control what parts of your code are exposed and how they interact with other parts of your application. This modular approach is crucial for building scalable and organized codebases.