How to import and export a module in TypeScript

Instead of writing all our codes in one file, we want everything to be properly organized and clean. This is where importing and exporting modules come in handy.

Export in TypeScript

There is a simple design/compile time tool that you can use to stop your TypeScript code from accessing things it should not. With the export keyword, JavaScript adds a line to include the exported item to the module.

There are two types of export statements: export default and normal export. They are similar, but have a few differences.

Normal export and import

export interface ITask{
taskName: string;
deadline: number;
}

In the example above, we simply export the interface to be used in another file.

The example below shows how we import it. We use the exact name, as used in the export statement, and destructure it.

import {ITask} from "./interfaces"

export default

Whenever we use export default, there are two ways in which the interfaces can be imported. We can either destructure each element (function) in the file and import it directly, or we can name the export and import it with the name or rename it.

Assume that we have a file called auth and in our auth.ts file, we have functions like logout() and login(). We wrap these elements in an object to export. This is shown below.

export default {login,logout};

We can import the modules like this:

import {login, logout} from "auth"

We can also import modules in a named pattern without restructuring.

import auth from "auth"

We can now use our functions in the auth file like:

auth.login();
auth.logout();

Named export and import

In TypeScript, we can export modules as a named export.

export default TodoTask;

Similarly, we can import these modules as:

import TodoTask from "../TodoTask"

Assuming we have functions like axios.get and axios.post, we can rename the export to be:

export default {
get: axios.get,
post: axios.post,
}

Hence, we can either import the whole object in a named way or in an unnamed way.

import {get,post} from "http";
//OR
import http from "http";

//we can now do 
http.get()
http.post()