TypeScript / TypeScript Modules and Namespaces

Exporting and Importing Functions, Classes, and Interfaces

In this tutorial, you’ll learn how to export and import functions, classes, and interfaces in TypeScript. This is crucial for creating reusable, clean, and maintainable code.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Covers the module system in TypeScript, including imports, exports, and namespaces.

Introduction

Welcome to this tutorial! Our goal today is to understand how to export and import functions, classes, and interfaces in TypeScript. These aspects are crucial in creating reusable, clean, and maintainable code by allowing us to break our code into modular chunks.

By the end of this tutorial, you will learn how to:

  • Export and import functions in TypeScript.
  • Export and import classes in TypeScript.
  • Export and import interfaces in TypeScript.

To make the most out of this tutorial, you should have a basic understanding of TypeScript and its syntax.

Step-by-Step Guide

In TypeScript, export and import are the two operators that allow us to create modular code. We use export to make parts of our code available for use in other files, and import to bring those exported parts into the current file.

Exporting Functions, Classes, and Interfaces

To export a function, class, or interface, we use the export keyword. Here's how to do it:

// Exporting a function
export function add(a: number, b: number): number {
  return a + b;
}

// Exporting a class
export class MyClass {
  constructor(private name: string) {}
  greet() {
    return `Hello, ${this.name}!`;
  }
}

// Exporting an interface
export interface MyInterface {
  name: string;
  age: number;
}

Importing Functions, Classes, and Interfaces

To import the exported functions, classes, or interfaces, we use the import keyword. Here's how to do it:

// Importing a function
import { add } from './myModule';

// Importing a class
import { MyClass } from './myModule';

// Importing an interface
import { MyInterface } from './myModule';

Code Examples

Now let's see some practical examples.

Example 1: Exporting and Importing a Function

// myModule.ts
export function add(a: number, b: number): number {
  return a + b;
}

// main.ts
import { add } from './myModule';
console.log(add(10, 20)); // This will output 30

In myModule.ts, we defined and exported a function add. Then, in main.ts, we imported the add function and used it.

Example 2: Exporting and Importing a Class

// myModule.ts
export class MyClass {
  constructor(private name: string) {}
  greet() {
    return `Hello, ${this.name}!`;
  }
}

// main.ts
import { MyClass } from './myModule';
const myInstance = new MyClass('John');
console.log(myInstance.greet()); // This will output 'Hello, John!'

In this example, we exported a MyClass class. We then imported the class in main.ts, created an instance of it, and used its greet method.

Example 3: Exporting and Importing an Interface

// myModule.ts
export interface MyInterface {
  name: string;
  age: number;
}

// main.ts
import { MyInterface } from './myModule';
let person: MyInterface = {name: 'John', age: 25};
console.log(person); // This will output { name: 'John', age: 25 }

In this example, we created an interface MyInterface and exported it. We then imported it in main.ts and created a person object of type MyInterface.

Summary

In this tutorial, we've covered the basics of exporting and importing functions, classes, and interfaces in TypeScript. We've learned how to use export to make parts of our code available for use in other files, and import to bring those exported parts into the current file.

To learn more about TypeScript, you can check the official TypeScript documentation.

Practice Exercises

  1. Create a module that exports a function, a class, and an interface. Then, import them in another module and use them.

  2. Create a module that exports multiple functions and classes. Then, import them in another module using import *.

  3. Create a module that exports a default function or class. Then, import it in another module without using curly braces.

Solutions and explanations for these exercises can be found in the official TypeScript documentation. After completing these exercises, you can practice more by creating your own modules and importing them in different parts of your application.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Fake User Profile Generator

Generate fake user profiles with names, emails, and more.

Use tool

Image Compressor

Reduce image file sizes while maintaining quality.

Use tool

Backlink Checker

Analyze and validate backlinks.

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help