How do import other TypeScript files? example
- Admin
- Mar 6, 2024
- Typescript
Sometimes, we may have a TypeScript code or class declared within a TypeScript file, and we want to import it into another file. This concept is crucial for code reusability.
TypeScript offers modules along with the export
and import
keywords to facilitate code reuse and exposure of files to external components.
Modules
, which are reusable code components, were originally introduced in JavaScript and have been adopted in TypeScript as well.
In TypeScript, the export
and import
keywords allow us to reuse classes, interfaces, functions, enums, and properties from other modules.
Let’s explore various methods of code reusability.
Single-class Export and Import
First, let’s declare a class and interface in Employee.Module.ts.
The export keyword is used to declare classes or functions that can be reused in other files.
Employee.Module.ts:
export class Employee {
id: number;
name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
printEmployeeInfo(): void {
console.log("Id = " + this.id + ", name = " + this.name);
}
}
In the TestEmployee.ts file, import the class using the import
keyword.
This way, a single class can be imported to utilize all the classes and functions within it.
TestEmployee.ts:
import { Employee } from "./Employee.Module";
let employee = new Employee(11, "John");
employee.printEmployeeInfo();
Importing All Classes and Interfaces using import * as
In this approach, we declare classes, functions, and interfaces in a file (Employee.Module.ts) and export them using the export
keyword.
Employee.Module.ts:
export class Lion {
printLion(): void {
console.log("animal class");
}
}
export interface Animal {
printAnimal(): void;
}
export function printCat() {
console.log("cat class");
}
Next, let’s import Employee.Module.ts into another file using the import * as
syntax.
TestEmp.ts
import * as Employee from "./Employee.module.ts";
let empObject = new Employee();
console.log(empObject.printLion()); //access class
console.log(Employee.printCat()); // use function
Single Function Export and Import using a Keyword
Now, let’s declare a function in Employee.module.ts and export it using the export keyword.
Employee.module.ts:
export function print() {
return "print an object";
}
We can then import this single function using the import keyword wrapped in braces syntax.
TestPrint.ts:
import { print as display } from "./Employee.module";
display();
Conclusion
In conclusion, we’ve learned how to import TypeScript files and reuse modules, classes, functions, interfaces, and properties in other TypeScript files.