Modules & Namespaces
TypeScript modules are files that share code with each other through import and export. Any file with a top-level import or export becomes a module. Modules keep your code organized, avoid name clashes, and let the compiler check that every import matches a real export. In real projects, modules are the backbone of every codebase, from a two-file script to a large application.
This tutorial covers what a module is, named vs default exports, import type, re-exporting, ES modules vs CommonJS, the module and moduleResolution options, namespaces and why modules are preferred, and declaration files with @types packages.
What Are TypeScript Modules?
A TypeScript module is a file with its own scope. Anything you want to share must be exported, and anything you want to use from another file must be imported. This explicit sharing keeps code predictable and prevents global name collisions.
Here is a quick example:
// mathUtils.ts
export function add(a: number, b: number): number {
return a + b;
}
// app.ts
import { add } from "./mathUtils.js";
console.log(add(2, 3));
// Output: 5
mathUtils.ts exports add. app.ts imports it and calls it. The import path ends with .js because the NodeNext module setting expects the final JavaScript extension, a point covered later.
How Do Named and Default Exports Work?
A named export exports a value under its own name, and you import it with braces. A default export exports one main value per file, and you import it without braces under any name. A file can have many named exports but only one default export.
// mathUtils.ts
export const PI = 3.14159;
export function add(a: number, b: number): number {
return a + b;
}
export default function multiply(a: number, b: number): number {
return a * b;
}
// app.ts
import multiply, { add, PI } from "./mathUtils.js";
console.log(add(2, 3));
console.log(multiply(4, 5));
console.log(PI);
// Output: 5
// Output: 20
// Output: 3.14159
How it works: add and PI are named exports, so they go inside braces. multiply is the default export, so it comes before the braces and you can rename it locally. If you tried to import { multiply }, the compiler would report that multiply is not a named export. Named exports are easier to refactor and give better autocomplete, so many teams prefer them for everything.
What Is import type and When Should You Use It?
import type imports only the type information and is erased at compile time. This matters when you want to use an interface or type alias without pulling the module's runtime code. It also helps with isolatedModules, where each file is compiled separately.
// types.ts
export interface User {
id: number;
name: string;
}
// app.ts
import type { User } from "./types.js";
const user: User = { id: 1, name: "Riya" };
console.log(user.name);
// Output: Riya
How it works: The import type line is removed entirely in the compiled JavaScript because User is only a type. If you used a regular import, some build tools might keep an unnecessary runtime import. Use import type for types and plain import for values. You can mix both with import { type User, createUser } when a module exports both.
How Do You Re-export from a Module?
Re-exporting lets a file forward exports from another module without importing and re-declaring them. This is common for building a public API from smaller internal files, often called a "barrel" file.
// mathUtils.ts
export function add(a: number, b: number): number {
return a + b;
}
export function subtract(a: number, b: number): number {
return a - b;
}
// index.ts
export { add, subtract } from "./mathUtils.js";
export type { User } from "./types.js";
// app.ts
import { add, subtract } from "./index.js";
console.log(add(5, 2), subtract(5, 2));
// Output: 7 3
How it works: index.ts re-exports the functions and the type from other files. Consumers import from ./index.js and do not need to know the internal file layout. This keeps imports stable when you move code around. Use export type { ... } for types so they are erased correctly.
ES Modules vs CommonJS: What Is the Difference?
ES modules use import and export and are the standard in modern JavaScript. CommonJS uses require and module.exports and is the older system used by Node.js before ES modules. TypeScript can output either format, controlled by the module option in tsconfig.json.
// ES module syntax
import { readFile } from "node:fs/promises";
export function load(path: string): Promise<string> {
return readFile(path, "utf8");
}
// CommonJS output (when "module": "CommonJS")
const promises_1 = require("node:fs/promises");
function load(path) {
return (0, promises_1.readFile)(path, "utf8");
}
exports.load = load;
How it works: With "module": "NodeNext", TypeScript emits ES modules for .mts files and CommonJS for .cts files, following Node.js rules. With "module": "ESNext", it emits ES modules and expects a bundler to handle the rest. The moduleResolution option controls how TypeScript finds the files behind your imports. "NodeNext" matches Node.js resolution; "Bundler" matches modern bundlers like Vite. Set both to match your runtime or build tool, or imports will fail.
What Are Namespaces and Why Prefer Modules?
A namespace is an older TypeScript construct that groups related code under one name without file-level modules. You write namespace MathUtils { export function add() {} } and access it as MathUtils.add. Namespaces predate ES modules and are still seen in older code, but modern projects should use modules instead.
namespace MathUtils {
export function add(a: number, b: number): number {
return a + b;
}
export const PI = 3.14159;
}
console.log(MathUtils.add(2, 3));
console.log(MathUtils.PI);
// Output: 5
// Output: 3.14159
How it works: The namespace creates a single object MathUtils with add and PI on it. Members must be marked export to be visible outside. Namespaces do not work with file-level imports by default and can produce global scripts. Modules are preferred because they align with the JavaScript ecosystem, work with bundlers and Node.js, and give better tree-shaking. Use namespaces only when maintaining older code or declaration files.
What Are Declaration Files and @types Packages?
A declaration file ends with .d.ts and contains only type information, no runtime code. It describes the shape of a JavaScript module so TypeScript can check code that uses it. Many popular libraries ship their own types; others are covered by @types packages installed from npm.
// custom.d.ts
declare module "my-lib" {
export function greet(name: string): string;
}
// app.ts
import { greet } from "my-lib";
console.log(greet("Riya"));
// Output: Hello, Riya
How it works: The declare module "my-lib" block tells TypeScript what my-lib exports, even if the library itself is plain JavaScript. The compiler uses this shape to check your calls. When a library has no types, install the matching package, such as npm install -D @types/node, and TypeScript finds it automatically. Declaration files are how the type system reaches into the JavaScript world.
Comparison: Modules vs Namespaces
| Feature | Modules | Namespaces |
|---|---|---|
Uses import/export |
Yes | No |
| Works with bundlers | Yes | Limited |
| Works with Node.js ES modules | Yes | Not directly |
| Global scope pollution | No | Possible |
| Tree-shaking friendly | Yes | No |
| Recommended for new code | Yes | No |
Modules are the modern choice for almost every case. Namespaces remain useful for very small scripts without a module system or for augmenting existing global types in declaration files.
Common Mistakes and Best Practices
- Forgetting the
.jsextension withNodeNext. WhenmoduleisNodeNext, imports must point to the final.jsfile, even though the source is.ts. Missing the extension gives a resolution error at compile time or runtime. - Mixing default and named imports incorrectly.
import multiply, { add }is valid;import { multiply }fails ifmultiplyis a default export. Pick one style per module and stay consistent. - Using regular
importfor types underisolatedModules. This can keep a runtime import that is no longer needed or cause an error. Useimport typefor types so the compiler removes them cleanly. - Setting
moduleandmoduleResolutioninconsistently."module": "NodeNext"expects"moduleResolution": "NodeNext". Mismatched values cause confusing resolution errors. Set both to match your runtime or bundler. - Using namespaces in new code. They work, but they do not interoperate well with modern tooling. Prefer modules so your code works with bundlers, Node.js, and the wider npm ecosystem.
Real-World Example: A Small Utility Module and Its Consumer
This example uses two files with named and default exports, a re-export barrel, and a short namespace for comparison.
// mathUtils.ts
export const PI = 3.14159;
export function add(a: number, b: number): number {
return a + b;
}
export default function multiply(a: number, b: number): number {
return a * b;
}
// index.ts
export { add, PI } from "./mathUtils.js";
export { default as multiply } from "./mathUtils.js";
// app.ts
import multiply, { add, PI } from "./index.js";
console.log(add(2, 3));
console.log(multiply(4, 5));
console.log(PI.toFixed(2));
// Output: 5
// Output: 20
// Output: 3.14
How it works, line by line. mathUtils.ts exports PI and add as named exports and multiply as the default export. index.ts re-exports all three, using export { default as multiply } to forward the default under a named export. app.ts imports multiply as the default and add and PI as named, all from the barrel. The compiler checks each import against the exports. When you compile with NodeNext, the import paths end in .js, and the output runs in Node.js. This is the standard module layout used by most TypeScript projects, and it keeps the public API in one place while the internals stay organized. The TypeScript with Node.js tutorial goes deeper into runtime and packaging details.
Summary
- TypeScript modules are files with
import/exportand their own scope, the standard way to share code. - Named exports use braces; default exports allow one main value per file and import without braces.
import typepulls only type information and is erased at compile time.- Re-exporting builds a clean public API from smaller internal files.
- Choose ES modules or CommonJS with the
moduleandmoduleResolutionoptions, and keep them consistent. - Namespaces are older and less compatible; prefer modules for new code.
- Declaration files (
.d.ts) and@typespackages describe JavaScript libraries so TypeScript can check them.
Now that you can split code across files, continue to the TypeScript Decorators tutorial to learn how to attach metadata and behavior to classes and methods.
Frequently Asked Questions
When does a TypeScript file become a module?
A file becomes a module as soon as it contains a top-level import or export. Without either, the file is treated as a global script, and its declarations share the global scope. Adding an empty export {} is a quick way to make a file a module without exporting anything.
Should I use default exports or named exports?
Named exports are usually better for refactoring and autocomplete, because the name is fixed and tools can track it. Default exports are convenient for a single main value per file, such as a component or a class. Many teams prefer named exports for everything and avoid defaults to keep imports predictable.
Can I mix import type and regular import in one line?
Yes. Write import { type User, createUser } from "./mod.js" to import a type and a value together. The type keyword before User tells the compiler to erase it, while createUser stays as a runtime import. Use import type { User } when the whole import is types only.
What is the difference between module and moduleResolution?
module controls what module format TypeScript emits, such as NodeNext, ESNext, or CommonJS. moduleResolution controls how TypeScript finds the files behind import paths, such as NodeNext or Bundler. Keep them consistent so that imports resolve the way your runtime or bundler expects.
Are namespaces still supported in TypeScript 5?
Yes. Namespaces are still supported and compile to JavaScript objects with the grouped members. They are not deprecated, but they are discouraged for new application code because they do not interoperate well with ES modules and bundlers. Use them for small scripts or declaration files, and use modules elsewhere.
Practice Exercises
Exercise 1 (Easy): Create a Named Export and Import
Create mathUtils.ts that exports add as a named export. Create app.ts that imports and calls it.
Show solution
// mathUtils.ts
export function add(a: number, b: number): number {
return a + b;
}
// app.ts
import { add } from "./mathUtils.js";
console.log(add(3, 4));
// Output: 7
The export keyword exposes add, and the braces in the import match the named export exactly.
Exercise 2 (Easy): Add a Default Export
Add a default multiply function to mathUtils.ts. Import it in app.ts alongside add.
Show solution
// mathUtils.ts
export function add(a: number, b: number): number {
return a + b;
}
export default function multiply(a: number, b: number): number {
return a * b;
}
// app.ts
import multiply, { add } from "./mathUtils.js";
console.log(add(1, 2), multiply(3, 4));
// Output: 3 12
The default export comes before the braces, and the named export stays inside the braces.
Exercise 3 (Medium): Re-export from a Barrel File
Create index.ts that re-exports add and multiply from mathUtils.ts. Import both from ./index.js in app.ts.
Show solution
// index.ts
export { add } from "./mathUtils.js";
export { default as multiply } from "./mathUtils.js";
// app.ts
import { add, multiply } from "./index.js";
console.log(add(5, 5), multiply(2, 6));
// Output: 10 12
The barrel re-exports the default under the name multiply, so consumers import everything as named exports from one place.
Exercise 4 (Challenge): Namespace and Module Comparison
Write a small namespace Strings with upper and lower functions. Then write the same functions as named exports in a module and import them. Compare the two call styles.
Show solution
namespace Strings {
export function upper(s: string): string {
return s.toUpperCase();
}
export function lower(s: string): string {
return s.toLowerCase();
}
}
console.log(Strings.upper("hi"));
// strings.ts
export function upper(s: string): string {
return s.toUpperCase();
}
export function lower(s: string): string {
return s.toLowerCase();
}
// app.ts
import { upper, lower } from "./strings.js";
console.log(upper("hi"));
console.log(lower("HI"));
// Output: HI
// Output: hi
The namespace call uses Strings.upper, while the module import uses the bare upper, which is clearer and works with bundlers.
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts.
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
