CPCODELAB
TypeScript

Modules in TypeScript

8 min read

Modules in TypeScript

TypeScript uses the same ES module syntax as modern JavaScript — import and export. Any file with a top-level import or export is treated as a module; files without either are scripts that share the global scope.

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

export const PI = 3.14159;

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

// main.ts
import subtract, { add, PI } from "./math";
import type { User } from "./types"; // type-only import (erased at compile time)

The import type syntax (TypeScript 3.8+) explicitly marks an import as type-only. The compiler strips these imports completely, which matters for bundlers and isolatedModules mode.

ts
// Re-exporting
export { add } from "./math";
export type { User } from "./types";

// Namespace import
import * as MathUtils from "./math";
MathUtils.add(1, 2);

When "moduleResolution": "NodeNext" is set, TypeScript requires explicit file extensions in relative imports (e.g., import { x } from "./utils.js" — note .js even though the source is .ts). Read the Next.js or Node.js docs for the conventions used in your project.

Ready to test yourself?
Practice TypeScript— quiz & coding exercises