TypeScript Modules

By default, the typescript code is in the global scope. If we have multiple files in a project, the variables, functions, etc. written in one file are accessible in all the other files.

TypeScript provides modules and namespaces in order to prevent the default global scope of the code and also to organize and maintain a large codebase.

What is TypeScript Module?

TypeScript Modules are a way to construct a local scope in a file. So that all the classes, variables declared in a module are not accessible outside the module.

👉 We can create a module using the export keyword.
👉 A module in typescript can be used in another module using the import keyword.

Export Module

The typescript module can be exported using the export keyword.

Let’s take an example of a Student class:

File: Student.ts

export class Student {
    readonly Id: number;
    Name: string;
    
    constructor(id: number, name: string) {
        this.Id = id;
        this.Name = name;
    }
}

let Subject: string = "Computer Science";

In the above example, the Student class is prefixed with the export keyword. So, the Student is now a module that can be imported and used in other modules.

The variable Subject won’t be available to use outside of the Student.ts file as it is not part of the module.

If we wish to use the Subject variable in another module, then we need to prefix it with the export keyword.

export let Subject: string = "Computer Science";

Import Module

We can import a module into another module using the import keyword.

Syntax:

import { export name } from "file path without the extension"

Example:

import { Student } from "./Student";

There are different ways to import a module in typescript.

  • Entire module to one variable
  • Single export from a module

Example:

//Entire module
import * as Std from "./Student";

//Single export
import { Student } from "./Student";

In the next section, we will learn about Generics in TypeScript.