EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials TypeScript Tutorial TypeScript module
Secondary Sidebar
TypeScript Tutorial
  • TypeScript Basic and Advanced
    • What is TypeScript?
    • Typescript Examples
    • TypeScript Versions
    • TypeScript Operators
    • JavaScript dump object
    • JavaScript get Method
    • Webpack ReactJS
    • Code Generator JavaScript
    • JavaScript Projects
    • Call Stack JavaScript
    • JavaScript Projects GitHub
    • JavaScript Filter Function
    • JavaScript nan
    • JavaScripttimestamp
    • TypeScript loop
    • CoffeeScript
    • TypeScript Webpack
    • setTimeout TypeScript
    • DHTMLX
    • CoffeeScript for loop
    • TypeScript number
    • JavaScript export module
    • TypeScript string contains
    • TypeScript Inheritance
    • TypeScript get
    • TypeScript undefined
    • TypeScript Global Variable
    • TypeScript Dictionary
    • TypeScript Generic
    • TypeScript Cast Object
    • TypeScript Optional Parameters
    • TypeScript? switch
    • TypeScript promise
    • TypeScript tuple
    • TypeScript Hashmap
    • TypeScript let
    • TypeScript Getter
    • TypeScript Pattern Matching
    • TypeScript number to string
    • TypeScript substring
    • TypeScript?lambda
    • TypeScript UUID
    • TypeScript JSDoc
    • TypeScript Decorators
    • Typescript for loop
    • TypeScript HTTP Request
    • TypeScript Abstract Class
    • TypeScript Question Mark
    • TypeScript Nullable
    • TypeScript reduce
    • TypeScript Mixins
    • TypeScript keyof
    • TypeScript string to number
    • TypeScript JSON parse
    • TypeScript const
    • TypeScript declare module
    • TypeScript String
    • TypeScript filter
    • TypeScript Multiple Constructors
    • TypeScript? Set
    • TypeScript string interpolation
    • TypeScript instanceof
    • TypeScript JSON
    • TypeScript Arrow Function
    • TypeScript generator
    • TypeScript namespace
    • TypeScript default parameter
    • TypeScript cast
    • TypeScript babel
    • Typescript Key-Value Pair
    • TypeScript if
    • TypeScript keyof Enum
    • TypeScript wait
    • TypeScript Optional Chaining
    • TypeScript JSX
    • TypeScript Version Check
    • TypeScript Unit Testing
    • TypeScript Handbook
    • TypeScript module
    • TypeScript Extend Interface
    • TypeScript npm
    • TypeScript pick
    • TypeScript Interface Default Value
    • JavaScript import module
    • Obfuscate Javascript
    • TypeScript basics
    • setInterval TypeScript
  • Type of Union
    • TypeScript Object Type
    • TypeScript type check
    • TypeScript promise type
    • TypeScript JSON type
    • TypeScript Union Types
    • TypeScript typeof
    • TypeScript Types
  • TypeScript Array
    • TypeScript Array of Objects
    • Methods TypeScript Array
    • TypeScript remove item from array
    • TypeScript add to array
    • TypeScript Array Contains
  • Function Of Array
    • TypeScript Function Interface
    • TypeScript Functions
    • TypeScript Export Function
    • TypeScript function return type

TypeScript module

TypeScript module

Introduction to TypeScript Module

TypeScript Modules is a file that contains functions, variables, or classes. These typescript modules are executed within their own scope and not in the global space. Starting with ECMAScript 2015, TypeScript has shared this concept of modules from JavaScript. Variables, classes, functions, etc. are declared in a modular way and are not visible outside the module unless and until these are explicitly exported using one of the available export forms. In the same way, consume any variable, class, function, or interface, etc. are exported from another module, hence these are to be imported using one of the available import forms.

Modules are decorative and relationships among modules are specified based on imports and exports at the file level. The module loader is responsible for locating the dependencies and executing dependencies of a module before executing at runtime. Some of the modern loaders used in JavaScript are NodeJS loaders for RequireJS loader and CommonJS modules for AM modules in web applications.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Modules are designed in such a manner so that code is organized, and these are divided into 2 modules,

  1. Internal Module
  2. External Module

These modules help to segment the applications, allow users to create small and independent reusable code. Also, modules know their own dependencies so that users can load modules when required in order.

Syntax:

Here is the Syntax for TypeScript Module, which are of two types; Import-Module and Export Module

Internal Module Statement:

Importing an exported declaration is done using one of the below import statements.

import { sample_file } from "./sample_file";

Import statements can also be renamed as below,

import { sample_file as sf } from "./sample_file";

This import module can also be used to import the entire module into a single variable as below,

import * as sample_file from "./sample_file";

External Module Statement:

Any particular declaration such as variables, functions, class, interfaces, or type aliases can be exported using the export keyword.

export interface sample_file {
}

For NodeJS applications, Modules are default and developers recommend modules over namespaces.

Examples of TypeScript module

Let us see how TypeScript Module work with few examples

Example #1 – Simple TypeScript Module example

In script.ts

export function multiple(x: number, y: number): number {
log(`${x} * ${y}`);
return x + y;
}
function log(message: string): void {
console.log("Numbers", message);
}

In index.ts

import { multiple } from "./script";
console.log('Value of x*y is:', multiple(4, 2));

Output:

TypeScript module output 1

We need to run the index.ts module as script.ts is imported into the index file.

Command to be used: tsc index.ts (this will create a .js file of itself, and then by using node command, we need to run the js file to see the output.

Example #2 – TypeScript Module Employee program

In Employee.ts

export interface Employee {
total();
}

In Company.ts

import employee = require("./Employee");
import employer = require("./Employer");
function drawAllShapes(shapeToDraw: employee.Employee) {
shapeToDraw.total();
}
drawAllShapes(new employer.Employer())

In Employer.ts

import employee = require("./Employee");
export class Employer implements employee.Employee {
public total() {
console.log("There are total of 500 employees in our Company");
}
}

Compilation Output:

On compiling the below commands,

tsc Employee.ts
tsc Employer.ts
tsc Company.ts

With these commands, .js files are created with the same names.

Employee.js, Employer.js, and Company.js files are created, as below

Employee.js

"use strict";
exports.__esModule = true;

Employer.js

"use strict";
exports.__esModule = true;
exports.Employer = void 0;
var Employer = /** @class */ (function () {
function Employer() {
}
Employer.prototype.total = function () {
console.log("There are total of 500 employees in our Company");
};
return Employer;
}());
exports.Employer = Employer;

Company.js

"use strict";
exports.__esModule = true;
var employer = require("./Employer");
function drawAllShapes(shapeToDraw) {
shapeToDraw.total();
}
drawAllShapes(new employer.Employer());

Output:

TypeScript module output 2

In TypeScript, as import and exports are available in Modules, re-exports also serve an important role i.e. exports other modules and expose the properties. Re-export is not importing locally or introducing a local variable. In such cases, re-exporting such cases either use original or rename it.

Example #3 – Student Details using TypeScript Module

In Student.ts

export class Student {
stuCode: number;
stuName: string;
constructor(name: string, code: number) {
this.stuName = name;
this.stuCode = code;
}
displayStudent() {
console.log ("Student Code: " + this.stuCode + ", Student Name: " + this.stuName );
}
}

In StudentDetails.ts

import { Student } from "./Student";
let empObj = new Student("Karthik", 101);
empObj.displayStudent();

Compilation Output:

On Compiling .ts files, JavaScript files are created as below

In Student.js

"use strict";
exports.__esModule = true;
exports.Student = void 0;
var Student = /** @class */ (function () {
function Student(name, code) {
this.stuName = name;
this.stuCode = code;
}
Student.prototype.displayStudent = function () {
console.log("Student Code: " + this.stuCode + ", Student Name: " + this.stuName);
};
return Student;
}());
exports.Student = Student;

In StudentDetails.js

"use strict";
exports.__esModule = true;
var Student_1 = require("./Student");
var empObj = new Student_1.Student("Karthik", 101);
empObj.displayStudent();

Output:

TypeScript module output 3

Conclusion

With this, we conclude our topic ‘TypeScript Module’. We have seen what the TypeScript module is and how it works. Syntactically checked both the various version of Modules, be it Internal or import syntax; External or export syntax. It is a very simple way to use modules in TypeScript; be it in understanding the dependencies between the components. While these native modules are not supported, users can simply use modules with SystemJS or RequireJS and migrate to Native form. As modules import one another using a module loader, at runtime, the module loader is responsible for locating and executing all the dependencies of modules before execution.

Recommended Articles

We hope that this EDUCBA information on “TypeScript module” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

  1. TypeScript Set
  2. TypeScript Question Mark
  3. TypeScript Dictionary
  4. TypeScript Generic
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more