Modules in TS

`import`, `export`, and `import type`

Modules in TS

TS modules are JS modules — same import/export — plus a couple of type-only refinements.

4 min read Level 1/5 #typescript#modules#import
What you'll learn
  • Export values and types from a module
  • Use `import type` for type-only imports
  • Know the difference between default and named exports

TS uses the same import / export syntax as ES modules. Every file is its own module. TS adds type-only variants.

Named Exports

// math.ts
export function add(a: number, b: number): number { return a + b; }
export const PI = 3.14159;
export type Vector = { x: number; y: number };
// app.ts
import { add, PI, type Vector } from "./math";

The type keyword on Vector says “this is only a type — erase the import.”

Default Exports

// logger.ts
export default class Logger { /* ... */ }
// app.ts
import Logger from "./logger";

Default exports work the same as JS — but the type ecosystem generally prefers named exports (better grep-ability, no rename inconsistency).

import type — Type-Only Imports

import type { User } from "./types";
import type * as T from "./types";

A pure type import. It’s guaranteed to be erased at compile time — no JS module is ever loaded. With verbatimModuleSyntax, this is the only way to import types.

Re-Exports

// index.ts — barrel file
export { add, PI } from "./math";
export type { Vector } from "./math";
export * from "./geometry";

Barrel files (index.ts that re-exports) are convenient but can hurt bundler tree-shaking. Use carefully.

Module Augmentation

Add fields to an existing module’s exports:

import "express";

declare module "express" {
  interface Request {
    user?: { id: string };
  }
}

Now req.user is typed across the whole app. Common pattern for middleware that attaches state to requests.

File Extensions

With allowImportingTsExtensions, you can import "./math.ts". Without it, you write import "./math". With ESM Node, import "./math.js" is required.

Modern projects increasingly require explicit extensions — follow whatever your bundler / Node config expects.

Up Next

Declaration files (.d.ts) — typing libraries that ship JS only.

Declaration Files →