How do import other TypeScript files? example
- Admin
- Sep 20, 2023
- Typescript
Sometimes, We have a code or class in typescript declared in a typescript, Want to import it to another file. It is a concept of reusing code.
Typescript provides the modules and export and import keywords to reuse and expose the files to the outside.
modules
are reusable code introduced in javascript
, The same is introduced in typescript
.
export
and import
keywords in typescript are used to reuse class
, interfaces
, functions
, Enum
, and properties
from another module
Let’s see different ways of reusable code.
Single-class export and import
declare class
and interfaces
in Employee.Module.ts
The export
keyword declares classes or functions that are ready to reuse in another file.
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 into it using the import
keyword
Included single class which can reuse all classes and functions of the class
TestEmployee.ts:
import { Employee } from "./Employee.Module";
let employee = new Employee(11, "John");
employee.printEmployeeInfo();
All classes and interfaces using import * as a keyword
In the file, Declared
- class
- function
- interface
All these are exported using the export
keyword in a separate file. Employee.Module.ts
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 as seen below
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
let’s declare a function in an Employee.module.ts and export using the export keyword. Employee.module.ts:
export function print() {
return "print an object";
}
Import this single function using import as wrapped in braces syntax.
TestPrint.ts:
import { print as display } from "./Employee.module";
display();
Conclusion
Learned how to import another typescript file and reuse modules classes, functions, interfaces, and properties in other typescript files.