TypeScript Modules

Note: If you're new to TypeScript, check our Getting Started with TypeScript tutorial first.


A TypeScript module is a file containing TypeScript code that can be imported and used in other TypeScript files.

For example, suppose we have two .ts files: square.ts and app.ts:

  • In square.ts, we define and export a function to square numbers, making this file a module.
  • Then, in app.ts, we import that squaring function from square.ts to use it.

Here, square.ts is a module.

Don't worry if you don't understand this right now. We will learn about these in detail below.


TypeScript Modules

Let's consider the two .ts files we discussed previously: square.ts and app.ts.

square.ts (The Module)

This file acts as a module by defining a function and making it available for use by other files. It contains the following:

// Function that calculates square of a number
export function square(number: number): number {
    return number * number;
}

Notice that we have used the export keyword to make this function available outside the square.ts file.

app.ts (Using the Module)

This file uses the function defined in the square.ts module. Inside the app.ts file, we import the square() function as:

// Import the square() function from the square.ts module
import { square } from './square';

// Use the imported function to compute the square 
console.log(square(4)); 

Notice that we have used the import keyword to bring in the square() function from the square.ts module.

Functions, objects, or types to be imported are enclosed within curly braces { } if they are named exports.

Note: When importing a module, you do not include the .ts extension — just the filename (e.g., import { square } from './square';).


Export Multiple Objects

It is also possible to export multiple objects from a module. For example,

In the file square.ts,

// Export the name variable
export const name: string = "TypeScript Program";

// Export the square() function
export function square(number: number): number {
    return number * number;
}

In app.ts file,

import { name, square } from './square';

console.log(name);
let result = square(6);
console.log(result); // 36

Here,

import { name, square } from './square';

This imports both the name variable and the square() function from the square.ts file.


Renaming Imports and Exports

If objects such as variables or functions you want to import have the same names as those already present in your main file, the program might not behave as expected.

In this case, the program takes value from the main file instead of the imported file.

To prevent naming conflicts, you can rename functions or variables either during export or import.

1. Rename in the Module (Export File)

Suppose we have a module file named module.ts. Inside the file, we can rename our objects to avoid conflicts.

Inside module.ts,

function checkStatus(): void {
    console.log("Checking status...");
}

function updateProfile(): void {
    console.log("Updating profile...");
}

// Export two functions with // new names to avoid conflicts export { checkStatus as getStatus, updateProfile as refreshProfile };

Here, we have given new names to the functions during export:

  • getStatus to the checkStatus() function
  • refreshProfile to the updateProfile() function

We can import them into our main file, main.ts, as:

Inside main.ts:

import { getStatus, refreshProfile } from './module';
getStatus(); // Checking status... refreshProfile(); // Updating profile...

2. Rename in the Import File

Alternatively, you can keep the original names in the module and choose new names when importing them into your main file.

Inside module.ts:

function checkStatus(): void {
    console.log("Checking status...");
}

function updateProfile(): void {
    console.log("Updating profile...");
}

// Export two functions with original names
export { checkStatus, updateProfile };

Inside main.ts:

// import two functions with new
// names to resolve naming conflicts
import { checkStatus as getStatus, updateProfile as refreshProfile } from './module';
getStatus(); // Checking status... refreshProfile(); // Updating profile...

Default Export

In TypeScript modules, a default export allows you to specify a single primary item (function, class, object, etc.) to export from a file.

Inside module.ts,

function checkStatus(): void {
    console.log("Checking status...");
}

function updateProfile(): void {
    console.log("Updating profile...");
}

// Default export of updateProfile function
export default updateProfile;

Here, we have used the default keyword to default export the updateProfile() function.

Inside main.ts,

When we import a default export, we can name it whatever we like without using curly braces.

// Import the default export using any name (no curly braces needed)
import profileUpdater from './module';

profileUpdater(); // Output: Updating profile...

Note: A file can contain multiple named exports, but only one default export.


Frequently Asked Questions

Benefits of Using Modules

Some of the benefits of using modules are:

  • Improved Maintainability: Code is organized into separate files based on functionality, making it easier to manage and update.
  • Enhanced Reusability: Modules are designed to be reusable, allowing you to define functionality once and use it across multiple parts of your application or in different projects.
  • Clear Dependencies: By using imports and exports, modules clearly outline their dependencies, thus simplifying debugging and testing.
Modules Always Use Strict Mode

TypeScript modules use strict mode by default. For example, we cannot use undeclared variables within a module.

Suppose our module file is greet.ts:

export function greet(): void {
    // Attempt to use an undeclared variable
    // throws an error in strict mode
    message = "Hello";
    console.log(message);
}

In this module, the greet() function tries to assign a string "Hello" to an undeclared variable message.

Since greet.ts is a module, it runs in strict mode by default, and this behavior results in a compile-time error.


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges