← Back to TypeScript Course | Chapter 9: Modules and Namespaces | Lesson 2 of 7

Import and Export

TypeScript supports ES module import and export syntax for sharing code between files. You can export functions, variables, classes, interfaces, and types, then import them where needed.

Named Export Syntax

Writing export before a declaration makes it available to other modules as a named export, which other files can then bring in with a matching import statement. A single file can have as many named exports as it needs, each imported individually or together.

Example: Named Export Syntax

typescript
// utils.ts
export function add(a: number, b: number): number {
  return a + b;
}
export const VERSION = "1.0";

console.log(add(2, 3), VERSION);

Importing Multiple Values

Multiple named exports can be imported together inside curly braces in a single import statement, rather than requiring a separate import line for each individual export, keeping the top of a file's imports compact and easy to scan.

Example: Importing Multiple Values

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

// main.ts
// import { add, subtract } from "./utils";
console.log(add(5, 2), subtract(5, 2));

Export Lists

Declarations can be written first and exported later using a separate export list at the bottom of the file, which can make a module's public surface easier to scan at a glance.

Example: Export Lists

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

console.log(add(1, 1));

Re-exporting Values

A module can re-export declarations that it itself imported from another module, which is useful for creating a single central entry-point file that gathers scattered exports together.

Example: Re-exporting Values

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

// index.ts
// export { square } from "./math";
function square(x: number) { return x * x; }
console.log(square(4));

Type-Only Imports and Exports

Use import type and export type when a declaration is needed only for type checking, since these type-only imports are guaranteed to be stripped out entirely from the compiled JavaScript output.

Example: Type-Only Imports and Exports

typescript
interface User {
  name: string;
}
export type { User };

// main.ts
// import type { User } from "./user";
const u: User = { name: "Ravi" };
console.log(u.name);
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.