How Do Imports and Exports Work in TypeScript?

Learn How Do Imports and Exports Work in TypeScript? with practical examples, explanations, best practices, and real-world coding techniques.

Introduction to Imports and Exports

Imports and exports are fundamental features of TypeScript modules. They allow developers to divide an application into separate files, reuse code across different parts of a project, and control which declarations are available to other modules.

An export makes a declaration available outside its module. An import allows another module to access that exported declaration. You can export functions, variables, classes, interfaces, type aliases, and other supported declarations.

For example, a learning platform might keep course-related functions in one module, shared models in another, and application logic in a separate file. Imports and exports connect these modules without requiring all the code to exist in one large file.

1. Understanding Exports in TypeScript

The export keyword makes a declaration available to other modules. Without an export, a declaration inside a module generally remains private to that module's scope.

// math-utils.ts

export const platformName = "IgKnight";

export function add(
  first: number,
  second: number
): number {
  return first + second;
}

export class Calculator {
  multiply(first: number, second: number): number {
    return first * second;
  }
}

In this example, platformName, add, and Calculator are exported from math-utils.ts. Other modules can import these declarations and use them according to their types.

The export keyword can be used directly when declaring a variable, function, or class. You can also declare several items first and export them together later in the file.

// course-utils.ts

const category = "Programming";

function getCategory(): string {
  return category;
}

export { category, getCategory };

Both styles are valid. Exporting declarations at their definition makes each public declaration easy to identify, while exporting them together can make the module's public interface easier to review in one place.

2. Named Imports

Named imports are used to import declarations that were exported by name. The imported names must match the corresponding exports unless you use aliases.

// math-utils.ts

export const platformName = "IgKnight";

export function add(
  first: number,
  second: number
): number {
  return first + second;
}

export function subtract(
  first: number,
  second: number
): number {
  return first - second;
}
// app.ts

import {
  platformName,
  add,
  subtract
} from "./math-utils";

console.log(platformName);
console.log(add(20, 10));
console.log(subtract(20, 10));

The curly braces identify a set of named imports. You can import one declaration or several declarations from the same module.

Named imports are useful when a module exposes several related functions, utilities, models, or constants. They make the origin and purpose of dependencies explicit.

The module path identifies the source file or package. Depending on the project, imports may use relative paths, package names, path aliases, or explicit file extensions required by the runtime or build configuration.

3. Import Aliases Using as

Sometimes different modules export declarations with the same name. Import aliases allow you to rename an imported declaration locally without changing its original export.

// course-utils.ts

export function formatName(name: string): string {
  return name.trim().toUpperCase();
}
// user-utils.ts

export function formatName(name: string): string {
  return name.trim().toLowerCase();
}
// app.ts

import {
  formatName as formatCourseName
} from "./course-utils";

import {
  formatName as formatUserName
} from "./user-utils";

console.log(formatCourseName("TypeScript"));
console.log(formatUserName("ASHA"));

Both modules export a function named formatName, but the importing file gives them different local names. This prevents a naming conflict and makes the intended operation clearer.

Aliases are useful when integrating third-party libraries, combining feature modules, or importing declarations whose original names are too generic for the current context.

You can also rename an exported declaration when defining the module's public interface. For example, export { internalName as publicName } allows a module to expose a different name without changing its internal implementation.

4. Default Exports

A module can provide one default export. This is commonly used when a file has one primary function, class, or value that represents its main purpose.

// course.ts

export default class Course {
  constructor(
    public id: number,
    public title: string
  ) {}

  getTitle(): string {
    return this.title;
  }
}

You can import the default export without curly braces:

// app.ts

import Course from "./course";

const course = new Course(101, "TypeScript");

console.log(course.getTitle());

The importing file chooses the local name for a default export. For example, another module could import the same class using the name LearningCourse.

Default exports are useful when one declaration is the main purpose of a file. Named exports are often a better fit when several declarations are equally important and should be imported by their explicit names.

Avoid creating multiple competing conventions throughout a large project. A consistent export style makes imports easier to read and simplifies refactoring.

5. Importing Named and Default Exports Together

A module can expose both a default export and named exports. Consumers can import both in the same statement when they need multiple declarations from that module.

// course.ts

export const platformName = "IgKnight";

export function getCourseCount(courses: string[]): number {
  return courses.length;
}

export default class Course {
  constructor(
    public id: number,
    public title: string
  ) {}
}
// app.ts

import Course, {
  platformName,
  getCourseCount
} from "./course";

const course = new Course(101, "TypeScript");

console.log(platformName);
console.log(course.title);
console.log(getCourseCount(["HTML", "CSS", "TypeScript"]));

The default import appears before the named imports. The named declarations are enclosed in curly braces, and all are imported from the same module.

This form is useful when a module has one primary class or function and also provides supporting utilities. However, a file does not need to provide both kinds of exports unless doing so improves the design of its public API.

6. Exporting and Importing Interfaces and Types

TypeScript lets modules export interfaces and type aliases so other files can use the same type definitions. This helps maintain consistent data structures across application services, components, and utilities.

// models.ts

export interface User {
  id: number;
  name: string;
  email: string;
}

export type UserRole = "admin" | "student" | "instructor";
// user-service.ts

import type { User, UserRole } from "./models";

export function getUserLabel(user: User): string {
  return user.id + ": " + user.name;
}

export function canManageCourses(role: UserRole): boolean {
  return role === "admin" || role === "instructor";
}

The models module defines reusable types, while user-service.ts imports them to describe function parameters and return values. If the User structure changes, consumers of that interface can receive corresponding type diagnostics.

The import type syntax explicitly indicates that the imported declarations are needed only for type checking. Interfaces and type aliases do not produce JavaScript runtime values.

For larger applications, sharing types across modules can reduce duplication and improve consistency. Keep shared type files organized around meaningful domain concepts instead of allowing one file to become a collection of unrelated definitions.

7. Type-Only Imports and Exports

Type-only imports and exports make a distinction between declarations needed for type checking and values needed at runtime. This matters because TypeScript removes type-only constructs during ordinary compilation to JavaScript.

// course-model.ts

export interface Course {
  id: number;
  title: string;
}

export type CourseStatus = "draft" | "published";
// course-service.ts

import type { Course, CourseStatus } from "./course-model";

export function getCourseTitle(course: Course): string {
  return course.title;
}

export function getStatus(course: Course): CourseStatus {
  return course.title.length > 0 ? "published" : "draft";
}

The service uses Course and CourseStatus only as types. Those declarations are not imported as runtime objects, while the functions themselves remain runtime values.

You can also use export type to re-export types from another module:

// public-types.ts

export type { Course, CourseStatus } from "./course-model";

Type-only syntax is particularly useful in projects that use strict module settings. It also helps prevent mistakes caused by assuming that an interface or type alias exists as a JavaScript value.

Remember that some declarations, such as classes, have both a type meaning and a runtime value. Use a normal import when the runtime class is required, and a type-only import when you need only its type.

8. Namespace Imports

A namespace import collects a module's exported declarations into a single local object-like namespace. It uses the syntax import * as followed by a local name.

// math-utils.ts

export function add(first: number, second: number): number {
  return first + second;
}

export function multiply(first: number, second: number): number {
  return first * second;
}

export const version = "1.0";
// app.ts

import * as MathUtils from "./math-utils";

console.log(MathUtils.add(10, 5));
console.log(MathUtils.multiply(10, 5));
console.log(MathUtils.version);

The MathUtils namespace import groups the exported declarations under one local name. Each declaration is accessed using dot notation.

This style can help when working with utility modules that expose many related operations. However, named imports often make dependencies more explicit when a file uses only a few declarations.

Namespace imports from ECMAScript modules are different from TypeScript's older internal namespace mechanism. For ordinary application code, prefer standard module imports and exports unless a namespace provides a clear benefit or is required by a particular library.

9. Re-Exports and Export Aliases

Re-exports allow a module to expose declarations from another module without implementing them again. They are useful when creating a public entry point for a collection of related functions or types.

// string-utils.ts

export function capitalize(value: string): string {
  return value.length > 0
    ? value[0].toUpperCase() + value.slice(1)
    : value;
}
// number-utils.ts

export function double(value: number): number {
  return value * 2;
}
// utils.ts

export { capitalize } from "./string-utils";
export { double } from "./number-utils";

Another module can now import both functions from the single entry point:

// app.ts

import { capitalize, double } from "./utils";

console.log(capitalize("typescript"));
console.log(double(10));

The utils module provides an organized public interface without duplicating the original implementations. You can also rename re-exported declarations using as.

// public-utils.ts

export { capitalize as capitalizeText } from "./string-utils";

Re-exports are particularly useful for library APIs and feature directories. Use them intentionally, however, so the public interface does not expose internal details that should remain private.

10. Side-Effect Imports

Not every import needs to retrieve a named export. A side-effect import loads a module for its initialization behavior without importing a specific declaration.

// initialize.ts

console.log("Application initialization module loaded");

export const initialized = true;
// app.ts

import "./initialize";

console.log("Application started");

The import loads the initialization module according to the runtime or bundler's module semantics. The importing file does not bind the initialized export to a local name.

Side-effect imports are commonly used for global styles, polyfills, instrumentation, and registration modules. Use them carefully because the importing file depends on behavior that may not be obvious from a named function call.

Bundlers and package configurations can affect whether apparently unused modules are preserved in the final output. Do not assume that every imported module will have the same behavior in every production build without checking the relevant tool configuration.

11. Dynamic Imports

Static imports declare dependencies at the module's top level. Dynamic imports use the import() expression to load a module asynchronously when the code needs it.

// report.ts

export function generateReport(): string {
  return "Report generated successfully";
}
// app.ts

async function loadReport(): Promise {
  const reportModule = await import("./report");

  console.log(reportModule.generateReport());
}

void loadReport();

The import() expression returns a promise that resolves to the module namespace object. The application can then call the exported function from that object.

Dynamic imports can be useful for route-based code splitting, optional features, large libraries, and operations that should only load when requested.

Although bundlers commonly use dynamic imports to create separate chunks, the actual loading strategy depends on the build system and runtime. Use them when conditional or asynchronous module loading makes sense for the application rather than assuming that every dynamic import automatically improves performance.

12. Module Paths and Configuration

Imports can refer to relative files, installed packages, or configured path aliases. The module path tells TypeScript and the project's tooling where a declaration or runtime module should be resolved.

// Relative import
import { formatName } from "../utils/format-name";

// Package import
import { someFunction } from "some-library";

// Example path alias
import type { Course } from "@models/course";

Relative paths describe a file's location in relation to the current module. Package imports refer to dependencies, while path aliases can provide shorter names for frequently used locations.

TypeScript supports path mapping through compiler configuration, but paths alone generally do not rewrite import specifiers in emitted JavaScript. Your runtime, bundler, or test tooling must support the same alias mapping when necessary.

Module resolution settings should match the actual project environment. A Node.js ESM application, a CommonJS project, and a browser application using a bundler may require different conventions for imports and file extensions.

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "strict": true,
    "noEmit": true
  },
  "include": ["src/**/*"]
}

This example is intended for a bundler-based project that handles output. Other configurations may need different module and module-resolution settings. The noEmit option prevents TypeScript from generating output files; it is not appropriate when the project relies on tsc to emit JavaScript.

13. Common Import and Export Errors

Importing a name that is not exported

Check the source module's export declarations and verify that the imported name matches. If the module provides a default export, use default import syntax instead of a named import.

Using curly braces incorrectly

Named imports use curly braces, while default imports do not. Confirm which kind of export the source module actually provides.

Import path cannot be resolved

Check the file path, filename capitalization, package installation, file extension requirements, and module-resolution settings. The correct fix depends on the runtime or bundler.

Importing an interface as a runtime value

Interfaces and type aliases are removed from ordinary JavaScript output. Use import type when you only need type information and a normal import when the code requires an actual runtime value.

Circular module dependencies

Modules that import each other can create difficult initialization order and dependency problems. Consider moving shared declarations to a lower-level module or restructuring the dependency graph.

Path aliases work only in the editor

TypeScript may resolve an alias that the runtime or bundler does not. Configure the relevant tooling consistently and verify that the application can load the resulting imports.

Best Practices for Imports and Exports

  • Keep modules focused on a clear feature or responsibility.
  • Use named exports for modules that expose several related declarations.
  • Use default exports when one primary declaration represents the module's purpose.
  • Use import type and export type to clarify dependencies that exist only for type checking.
  • Rename imported declarations with aliases when names conflict or local clarity improves.
  • Use re-exports and barrel files selectively to define intentional public APIs.
  • Avoid circular dependencies and unnecessary cross-feature imports.
  • Ensure module settings, file extensions, and path aliases match the actual runtime and build system.
  • Use dynamic imports for conditional loading when it provides a practical benefit.
  • Export only the declarations that consumers genuinely need instead of exposing every internal implementation detail.

Conclusion

Imports and exports allow TypeScript developers to create modular applications with clear dependencies and reusable code. Named exports, default exports, aliases, type-only imports, namespace imports, re-exports, and dynamic imports provide different ways to expose and consume module functionality.

Start by separating related functionality into focused files, exporting only what other modules need, and importing dependencies explicitly. As your project grows, use type-only imports for shared types, establish consistent module conventions, and verify that paths and configuration work with your actual build system. These practices make TypeScript applications easier to understand, test, and maintain.

Code Examples

Named Exports and Imports

typescript
// math-utils.ts
export function add(first: number, second: number): number {
  return first + second;
}

export function multiply(first: number, second: number): number {
  return first * second;
}

// app.ts
import { add, multiply } from "./math-utils";

console.log(add(10, 20));
console.log(multiply(10, 20));
    

Named exports allow a module to expose multiple declarations that can be imported by their original names.

Default Export

typescript
// course.ts
export default class Course {
  constructor(
    public id: number,
    public title: string
  ) {}

  getTitle(): string {
    return this.title;
  }
}

// app.ts
import Course from "./course";

const course = new Course(101, "TypeScript");

console.log(course.getTitle());
    

A default export is useful when one class, function, or value is the primary declaration provided by a module.

Import Aliases

typescript
// string-utils.ts
export function formatName(name: string): string {
  return name.trim().toUpperCase();
}

// app.ts
import {
  formatName as formatCourseName
} from "./string-utils";

console.log(formatCourseName("typescript"));
    

The as keyword assigns a local name to an import without changing the exported declaration in the original module.

Type-Only Imports

typescript
// models.ts
export interface Course {
  id: number;
  title: string;
}

// course-service.ts
import type { Course } from "./models";

export function getCourseTitle(course: Course): string {
  return course.title;
}

const course: Course = {
  id: 101,
  title: "TypeScript"
};

console.log(getCourseTitle(course));
    

The import type statement imports a declaration specifically for type checking, without requiring an interface as a runtime value.

Re-Exports Through a Barrel File

typescript
// string-utils.ts
export function capitalize(value: string): string {
  return value.length > 0
    ? value[0].toUpperCase() + value.slice(1)
    : value;
}

// number-utils.ts
export function double(value: number): number {
  return value * 2;
}

// utils.ts
export { capitalize } from "./string-utils";
export { double } from "./number-utils";

// app.ts
import { capitalize, double } from "./utils";

console.log(capitalize("typescript"));
console.log(double(10));
    

A barrel file re-exports declarations from separate modules to provide consumers with one convenient public entry point.

Dynamic Imports

typescript
// report.ts
export function generateReport(): string {
  return "Report generated successfully";
}

// app.ts
async function loadReport(): Promise<void> {
  const reportModule = await import("./report");

  console.log(reportModule.generateReport());
}

void loadReport();
    

The import() expression loads a module asynchronously and resolves to an object containing its exported declarations.

Pro Tip

Use named exports for shared utilities and models, default exports when a module has one clear primary declaration, and import type for declarations needed only during type checking. Keep module paths consistent with your runtime or bundler, and avoid barrel files that create unnecessary circular dependencies.

More TypeScript lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.