TExcelTAD
Home › TypeScript › TS Modules

TypeScript Modules

As a program grows you split it into files. In modern TypeScript every file that contains a top-level import or export is a module: its variables, functions and types are private to the file unless you export them, and other files bring them in with import. TypeScript uses the standard ECMAScript module syntax and adds a few type-only features on top.

Exporting and importing

Here is a small project with two files. math.ts exports a constant, a function, a type and a default export:

ts
// math.ts
export const PI = 3.14159;

export function circleArea(radius: number): number {
  return PI * radius * radius;
}

export interface Shape {
  kind: string;
  area(): number;
}

export default function round2(n: number): number {
  return Math.round(n * 100) / 100;
}

app.ts imports what it needs. Named exports go in braces; the default export gets whatever name you choose:

ts
// app.ts
import round2, { circleArea, PI, type Shape } from "./math.js";
import * as geometry from "./math.js";   // namespace import

const disk: Shape = { kind: "disk", area: () => circleArea(2) };
console.log(round2(disk.area()));        // 12.57
console.log(geometry.PI === PI);         // true

Note: With "module": "nodenext" you write the .js extension in import paths even though the source file is .ts. TypeScript resolves ./math.js to math.ts at compile time, and the path is then correct for the emitted JavaScript. Bundlers such as Vite ("moduleResolution": "bundler") let you leave the extension off.

Syntax Meaning
export const x = … named export
export default … one default export per module
export { a, b as c } export existing names, optionally renamed
export * from "./x.js" re-export everything (a "barrel" file)
import { a } from "./x.js" named import
import x from "./x.js" default import
import * as ns from "./x.js" all exports as one object
import type { T } from "./x.js" type-only import, erased from the output

Modules have their own scope

A file without any import/export is treated as a global script: its top-level declarations share one global scope with every other script and with the built-in browser types. That can cause surprising clashes. The browser's lib already declares a global called name, so this script fails:

ts
// script.ts: no import or export anywhere in the file
const name = "Lan";
console.log(name);
text
$ npx tsc script.ts
script.ts(2,7): error TS2451: Cannot redeclare block-scoped variable 'name'.

Note: The ExcelTAD playground type-checks every example as a module (the same as "moduleDetection": "force", see the tip below), because examples run as ES modules. So the clash above only shows up when you compile a script file with tsc yourself.

Adding any export — even an empty export {} — turns the file into a module with its own scope, and the error disappears:

ts · try it yourself
export {};

const name = "Lan";
console.log(`Hello, ${name}`);
Hello, Lan

Tip: Real projects should be made of modules only. Setting "moduleDetection": "force" in tsconfig.json treats every file as a module, even without imports.

Type-only imports and exports

Types don't exist at runtime, so importing an interface produces no JavaScript at all. Marking such imports with type makes that explicit and lets tools remove them safely. With the verbatimModuleSyntax option (recommended for new projects) it is required:

ts
// user.ts
export interface User { id: number; email: string }
export function makeUser(id: number, email: string): User {
  return { id, email };
}

// main.ts
import { makeUser, type User } from "./user.js";  // inline type modifier
import type { User as Person } from "./user.js";  // whole import is type-only

Exporting from a single file

The playgrounds on this site are one module, but you can still use export to see how exported declarations behave. Exports are simply ordinary declarations that are also visible to importers:

ts · try it yourself
export type Currency = "VND" | "USD";

export interface Price {
  amount: number;
  currency: Currency;
}

export function format(p: Price): string {
  return p.currency === "USD" ? `${p.amount.toFixed(2)}` : `${p.amount.toLocaleString("en-US")} ₫`;
}

const items: Price[] = [
  { amount: 4.5, currency: "USD" },
  { amount: 125000, currency: "VND" },
];
items.map(format).forEach((s) => console.log(s));
$4.50
125,000 ₫

Dynamic import

import() used as an expression loads a module on demand and returns a promise. TypeScript knows the module's type, so the result is fully typed:

ts
async function loadChart() {
  const { drawChart } = await import("./chart.js");  // typed as typeof import("./chart.js")
  drawChart([3, 1, 4]);
}

Dynamic imports are how bundlers split code into chunks that load only when needed.

Namespaces (legacy)

Before ES modules, TypeScript offered namespace blocks to group code under one global name. You will still see them in old code and in declaration files, but new code should use modules:

ts · try it yourself
namespace Units {
  export const cmPerInch = 2.54;
  export function toCm(inches: number) {
    return inches * cmPerInch;
  }
}

console.log(Units.toCm(10));
25.4

Test yourself

What turns a TypeScript file into a module?

  1. Naming it *.module.ts
  2. Any top-level import or export
  3. A namespace block
  4. Using const instead of var

What does import type { User } from "./user.js" produce in the emitted JavaScript?

  1. A normal import
  2. Nothing — it is erased
  3. A require() call
  4. A runtime type check

With "module": "nodenext", how do you import math.ts from a neighbouring file?

  1. "./math"
  2. "./math.ts"
  3. "./math.js"
  4. "math"