TypeScript / TypeScript Modules and Namespaces

Using Default and Named Exports

This tutorial will teach you how to use default and named exports in TypeScript. These exports allow you to create more flexible and organized code.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

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

Using Default and Named Exports in TypeScript

Introduction

In this tutorial, we aim to teach you how to use default and named exports in TypeScript, a key concept for managing and organizing your codebase.

By the end of this lesson, you will be able to:
- Understand the differences between default and named exports.
- Know how to use default and named exports in your TypeScript projects.

Prerequisites: Basic understanding of TypeScript is required before you start this tutorial.

Step-by-Step Guide

What are Default and Named Exports?

In TypeScript, you can have multiple named exports per module but only one default export.

  • A default export is an export that's been designated as the main exported value.
  • Named exports are useful to export several values.

Using Default Exports

Default exports are declared using the default keyword. They can be function, class, interface, enum, or any other valid TypeScript declaration.

// myModule.ts
export default function() { console.log("Hello, World!"); }

In the code above, the function is the default export of the module. You can import it like so:

// main.ts
import myFunc from './myModule';
myFunc(); // Outputs: "Hello, World!"

Using Named Exports

Named exports can be any valid TypeScript declaration, just like default exports. You can have multiple named exports per module.

// myModule.ts
export function greet() { console.log("Hello, World!"); }
export const name = 'John';

You can import named exports individually like so:

// main.ts
import { greet, name } from './myModule';
greet(); // Outputs: "Hello, World!"
console.log(name); // Outputs: "John"

Code Examples

Now, let's see some more practical examples.

Default Export

// rectangle.ts
export default class Rectangle {
  constructor(public width: number, public height: number) {}

  getArea() {
    return this.width * this.height;
  }
}

Here, the Rectangle class is the default export. You can import it as follows:

// main.ts
import Rectangle from './rectangle';

const myRectangle = new Rectangle(5, 4);
console.log(myRectangle.getArea()); // Outputs: 20

Named Exports

// shapes.ts
export class Circle {
  constructor(public radius: number) {}

  getArea() {
    return Math.PI * this.radius ** 2;
  }
}

export class Square {
  constructor(public side: number) {}

  getArea() {
    return this.side ** 2;
  }
}

You can import and use the named exports as follows:

// main.ts
import { Circle, Square } from './shapes';

const myCircle = new Circle(5);
console.log(myCircle.getArea()); // Outputs: 78.53981633974483

const mySquare = new Square(4);
console.log(mySquare.getArea()); // Outputs: 16

Summary

In this tutorial, we learned about default and named exports in TypeScript. You learned how to declare and use both types, with practical examples.

For further learning, you might want to explore:
- How to use these exports in larger TypeScript projects.
- How to handle cases where you want to rename imports or exports.

Practice Exercises

  1. Exercise: Create a module with a default export of a function that returns the string 'Hello, World!', and a named export of a constant named greeting with the value 'Hello'.

Solution:
```typescript
// helloWorld.ts
export default function() {
return 'Hello, World!';
}

export const greeting = 'Hello';
```

  1. Exercise: Import the default function and the greeting constant from the module you created in the previous exercise, and use them to print 'Hello, World!' to the console.

Solution:
```typescript
// main.ts
import helloWorld, { greeting } from './helloWorld';

console.log(greeting + ', ' + helloWorld()); // Outputs: "Hello, Hello, World!"
```

Keep practicing these concepts until you feel comfortable with them. Happy coding!

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

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

File Size Checker

Check the size of uploaded files.

Use tool

Image Compressor

Reduce image file sizes while maintaining quality.

Use tool

Fake User Profile Generator

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

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