Wednesday, July 3, 2024
HomeLanguagesJavascriptHow to allow classes defined in a module to be accessible outside...

How to allow classes defined in a module to be accessible outside of a module ?

In typescript by using an import statement, a module can be utilized in another module. any variables, classes, methods, or other objects declared in a module are not accessible outside of it. The keyword “export” may be used to construct a module, and the term “import” can be used to import it into another module. Let’s demonstrate how to do this.

Export: A separate.ts file may be used to create a module, which can have variables, methods, and classes. With all the definitions you intend to include in a module and access from other modules, the prefix export must be used before them

The below code is kept in a typescript file called student.ts. This module has two variables and a class called student. The variable section can be used in another module as it is prefixed with the keyword “export” but the student_name variable cannot be accessed in another module as it is not prefixed with the keyword “export”.

Javascript




export let section: number = 9;
export class Student {
    student_id: number;
    name: string;
    constructor(name: string, id: number) {
        this.name = name;
        this.student_id = id;
    }
    displayStudentDetails() {
        console.log(
            "student_id: " + `${this.student_id}` + ", 
                Student Name: " + this.name
        );
    }
}
  
let student_name: string = "aditi";


Import: Variables, classes, etc.. can be accessed from the other class by the current module using the “import” keyword.

Syntax:

Import { name_of_the_class_or_variable_being_exported } from "file_path"
file_path : file path should be specified without any extension.

we can import only those methods, variables, or classes that are prefixed by the keyword “export”.

Example 1:

  • Importing a Module’s Single Export: In this example, class Student is imported from the student.ts module. no other variables which are from student.ts get imported. This file can be named studentImport.ts. 

Javascript




import { Student } from "./student";
  
let Object = new Student("richa", 61);
console.log(Object.displayStudentDetails());


Output:

student_id: 61, Student Name: richa
  • Importing the entire module: In this example, we import all the exports from the module. The * syntax is used to import all the exports from the previous module. 

Javascript




import * as stu from "./student";
  
let Object = new stu.Student("richa", 61);
console.log(Object.displayStudentDetails());
  
let variable = stu.section;
console.log(variable);


Output:

student_id: 61, Student Name: richa
undefined
9

What if we try importing student_name which is not prefixed with keyword export?. typescript compiler raises an error. 

Javascript




import * as stu from "./student";
  
// let Object = new stu.Student("richa", 61);
// console.log(Object.displayStudentDetails());
  
let variable = stu.student_name;
console.log(variable);


Output:

error TS2339: Property 'student_name' does not exist on type 'typeof import("/Users/...")'.
6 let variable = stu.student_name;

Changing the name of a module’s export: Here, ‘as’ keyword is used to change the name of the export. Sometimes we’d like to rename our exports to much simpler names, in such cases we can rename exports as given in the below example. This code is in studentImport.ts. 

Javascript




import { Student as S } from "./three";
  
let Object = new S("richa", 61);
console.log(Object.displayStudentDetails());


Output:

student_id: 61, Student Name: richa
undefined

Note on compilation: First the typescript file which has the import statements must be compiled in the terminal.

tsc studentImport.ts

Then the javascript file created must be compiled using the below command:

node studentImport.js

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Shaida Kate Naidoo
am passionate about learning the latest technologies available to developers in either a Front End or Back End capacity. I enjoy creating applications that are well designed and responsive, in addition to being user friendly. I thrive in fast paced environments. With a diverse educational and work experience background, I excel at collaborating with teams both local and international. A versatile developer with interests in Software Development and Software Engineering. I consider myself to be adaptable and a self motivated learner. I am interested in new programming technologies, and continuous self improvement.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments