Typescript Default And Named Exports Complete Guide

 Last Update:2025-06-22T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    7 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of TypeScript Default and Named Exports

Overview

TypeScript, being a statically-typed superset of JavaScript, extends JavaScript's modular system by introducing robust mechanisms for exporting and importing code chunks. The two primary types of exports in TypeScript are Default Exports and Named Exports. Understanding them is pivotal for organizing and sharing code within a project.

1. Named Exports

Named exports allow multiple exports per module. When importing, the imported entities must be matched by name.

Syntax for Named Exports

// module mathUtils.ts
export const pi = 3.14159;
export const sqrtTwo = 1.414;
export function sum(a: number, b: number): number {
    return a + b;
}

Syntax for Importing Named Exports

// main.ts or any other consuming module
// Import only the required names
import { pi, sum } from './mathUtils'; 

console.log(pi); // 3.14159
console.log(sum(3, 4)); // 7

// Import all named exports, useful when importing several things
// Note the curly braces disappointing that包围
import * as MathUtils from './mathUtils';

console.log(MathUtils.sqrtTwo); // 1.414

Importing with Aliases

TypeScript allows developers to use aliases to simplify the import or when avoiding namespace conflicts.

import { pi as Pi, sum as calculateSum } from './mathUtils'; 

console.log(Pi); // 3.14159
console.log(calculateSum(3, 4)); // 7

2. Default Exports

A module can have only one default export. While importing, the identifier used can be different from the name of the exported entity, which offers flexibility but must be used consistently within a module.

Syntax for Default Exports

// module mathematician.ts
const pi = 3.14159;
function sum(a: number, b: number): number {
    return a + b;
}
export default {
    pi,
    sum,
    greet(name: string): string {
        return `Hello, ${name}!`;
    }
};

Syntax for Importing Default Exports

import MathConstants from './mathematician';

console.log(MathConstants.pi); // 3.14159
console.log(MathConstants.sum(3, 4)); // 7
console.log(MathConstants.greet('Arthur')); // Hello, Arthur!

Naming Flexibility

import MathData from './mathematician';

console.log(MathData.pi); // 3.14159
console.log(MathData.sum(5, 6)); // 11
console.log(MathData.greet('John')); // Hello, John!

Guidelines and Best Practices

  • Consistency: Especially in large projects, maintaining consistency in how modules are named and imported leads to better readability and maintainability.

  • Use Default Exports Sparingly: Named exports are clearer in what they export and how to use them. Default exports should typically be used when there is a single, clear purpose of the module.

  • Combine Both for Flexibility: Modules can have both named and default exports, which can be mixed during import to satisfy different importing needs.

  • Tree Shaking: Tools like Webpack can perform tree shaking, removing unused code. Because of the explicit nature of named exports, they can be more effectively included or omitted during the bundling process.

Conclusion

Understanding TypeScript's default and named exports is fundamental for effective code structuring and sharing. By leveraging both export methods, developers can create modular, readable, and maintainable codebases. Proper usage of default and named exports aligns with modern web development practices, facilitating efficient development workflows.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement TypeScript Default and Named Exports

Step 1: Setting Up Your TypeScript Project

First, ensure you have TypeScript installed. If it's not already installed, you can install it globally using npm:

npm install -g typescript

Once TypeScript is installed, create a new directory for your project and navigate into it:

mkdir typescript-exports-example
cd typescript-exports-example

Initialize a new npm project:

npm init -y

Install TypeScript as a development dependency:

npm install typescript --save-dev

Next, set up a basic TypeScript configuration file (tsconfig.json) by running:

npx tsc --init

By default, the configuration will work, but you can adjust options in the tsconfig.json file as per your requirements.

Step 2: Creating a TypeScript Module with Named Exports

Named exports allow you to export one or more exports from a module. Here's an example:

utils.ts

Create a new file named utils.ts and add the following code:

// utils.ts

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

export function subtract(a: number, b: number): number {
    return a - b;
}

Step 3: Importing Named Exports

Create another file named app.ts where you will import the named exports from utils.ts.

app.ts

// app.ts

import { add, subtract } from './utils';

const result1 = add(5, 3);
console.log(`5 + 3 = ${result1}`); // Output: 5 + 3 = 8

const result2 = subtract(5, 3);
console.log(`5 - 3 = ${result2}`); // Output: 5 - 3 = 2

Step 4: Creating a TypeScript Module with a Default Export

Default exports allow you to have one "main" export per module, which can be imported without using curly braces. Here's an example:

calculator.ts

Create a new file named calculator.ts and add the following code:

// calculator.ts

export default class Calculator {
    public add(a: number, b: number): number {
        return a + b;
    }

    public subtract(a: number, b: number): number {
        return a - b;
    }
}

Step 5: Importing a Default Export

Create another file named main.ts where you will import the default export from calculator.ts.

main.ts

// main.ts

import Calculator from './calculator';

const calc = new Calculator();
const result1 = calc.add(10, 5);
console.log(`10 + 5 = ${result1}`); // Output: 10 + 5 = 15

const result2 = calc.subtract(10, 5);
console.log(`10 - 5 = ${result2}`); // Output: 10 - 5 = 5

Step 6: Running the TypeScript Code

Compile your TypeScript files to JavaScript using the TypeScript compiler (tsc). It will generate .js files:

npx tsc

Now, you will have compiled JavaScript files (utils.js, app.js, calculator.js, and main.js).

You can run the JavaScript code using Node.js:

node app.js

Expected output:

5 + 3 = 8
5 - 3 = 2

And:

node main.js

Expected output:

Top 10 Interview Questions & Answers on TypeScript Default and Named Exports

1. What are Default Exports in TypeScript?

Answer: In TypeScript, a default export allows you to export a single object, function, or primitive from a module. It can be imported with any name. Here's an example:

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

// main.ts
import subtract from './math'; // can import with any name
console.log(subtract(5, 3)); // This will still call the add function

Note that although you can name the import anything, sticking to meaningful names is a good practice.

2. Can a Module Have More Than One Default Export?

Answer: No, a module can have only one default export. Attempting to declare more than one default export will result in a syntax error.

3. What are Named Exports in TypeScript?

Answer: Named exports allow you to export multiple values from a module. Each export must have a unique name. Imports must use the exact same name.

// math.ts
export function subtract(a: number, b: number): number {
  return a - b;
}
export const PI = 3.14159;

// main.ts
import { subtract, PI } from './math';
console.log(subtract(10, 5)); // Outputs: 5
console.log(PI); // Outputs: 3.14159

4. Can You Mix Default and Named Exports in a Single Module?

Answer: Yes, you can mix default and named exports in the same module.

// math.ts
export default function multiply(a: number, b: number): number {
  return a * b;
}
export function divide(a: number, b: number): number {
  return a / b;
}

// main.ts
import multiply, { divide } from './math';
console.log(multiply(10, 2)); // Outputs: 20
console.log(divide(10, 2));   // Outputs: 5

5. How Do You Import All Named Exports from a Module?

Answer: To import all named exports from a module, you can use the asterisk (*) symbol with an alias.

// math.ts
export function square(a: number): number {
  return a * a;
}
export function cube(a: number): number {
  return a * a * a;
}

// main.ts
import * as MathFunctions from './math';
console.log(MathFunctions.square(3));  // Outputs: 9
console.log(MathFunctions.cube(2));    // Outputs: 8

6. Is It Possible to Rename Imports During Import Operations?

Answer: Yes, you can rename imports using the as keyword. This is useful when dealing with name clashes or when you want to improve readability.

// math.ts
export default function add(a: number, b: number): number {
  return a + b;
}
export function subtract(a: number, b: number): number {
  return a - b;
}

// main.ts
import sum, { subtract as diff } from './math';
console.log(sum(5, 2));   // Outputs: 7
console.log(diff(9, 3)); // Outputs: 6

7. How Do You Export a Variable or Function as Default That Was Previously Declared Separately?

Answer: You can use the export default syntax without the function or variable name if it’s already declared.

// math.ts
function add(a: number, b: number): number {
  return a + b;
}
const PI = 3.14159;
export { add as default, PI };
// main.ts
import add, { PI } from './math';
console.log(add(5, 5)); // Outputs: 10
console.log(PI); // Outputs: 3.14159

8. Can You Import the Default and Named Exports in a Single Import Statement?

Answer: Yes, you can use a combination of the default and named imports in a single import statement.

// math.ts (same as previous example)

// main.ts
import multiply, { PI, subtract } from './math';
console.log(multiply(7, 3));   // Outputs: 21
console.log(subtract(9, 5));   // Outputs: 4
console.log(PI);              // Outputs: 3.14159

9. What are the Use Cases for Default vs. Named Exports?

Answer: Typically, default exports are preferable when exporting a single primary class, function, or object that is the main export of a module. Named exports are used when you want to export multiple functions, classes, or variables from a module.

  • Default Exports: Often used when exporting a single entity, like a utility function or class.
  • Named Exports: Common when exporting multiple entities from a module for clarity.

10. How Do You Combine Named Exports from Different Modules into a Single Object?

Answer: You can combine named exports from different modules using the export keyword in a new module.

You May Like This Related .NET Topic

Login to post a comment.