DevAcademy
AdvancedTypeScript

Modules

Learn how to import and export types and values across files in TypeScript.

Reading Time

14 min

Lesson

Lesson 26 of 30

ES Modules Work the Same Way

TypeScript uses the same import/export syntax as modern JavaScript — the only addition is the ability to import and export types alongside regular values.

Exporting Values and Types

// user.ts
export interface User {
  id: number;
  name: string;
}

export function createUser(name: string): User {
  return { id: Date.now(), name };
}

Importing Values and Types

// main.ts
import { User, createUser } from "./user";

const user: User = createUser("Alice");

Type-Only Imports

The import type syntax explicitly imports only a type, guaranteeing the import is completely erased from the compiled JavaScript — useful for keeping bundles clean and avoiding accidental circular runtime dependencies.

Type-Only Import

import type { User } from "./user";
import { createUser } from "./user";

// 'User' is guaranteed to disappear entirely after compilation

Default Exports

TypeScript also supports default exports, imported without curly braces and given any local name.

Default Export

// logger.ts
export default function log(message: string): void {
  console.log(message);
}

// main.ts
import log from "./logger";
log("Hello");

Namespaces (Legacy)

Before ES modules were standard, TypeScript had its own module system called namespaces. They still exist for backward compatibility, but modern TypeScript code should use ES modules instead.

A Namespace (Avoid in New Code)

namespace MathUtils {
  export function square(n: number): number {
    return n * n;
  }
}

MathUtils.square(4); // 16

Avoid Namespaces in New Code

Namespaces predate ES modules and don’t integrate well with modern bundlers and tree-shaking. Use standard import/export for all new TypeScript code.

Best Practice

Use import type for imports that are only used as types, especially with isolatedModules enabled — it makes the type-only intent explicit and keeps compiled output as small as possible.

Interview Questions

Quick Quiz

1. Does TypeScript use a different import/export syntax from JavaScript?

2. What does import type guarantee?

3. Should new TypeScript projects use namespaces or ES modules?