Sub topic 2
Exporting and importing: named, default, and namespace forms
This chapter assumes you know basic TypeScript types and functions, have run tsc, and have seen JavaScript import and export statements. It covers the three ways a TypeScript module shares values with other modules, how each one is written, and the mistakes that come up most often.
The shape of a module's public surface
A file with a top-level import or export is a module. Everything inside it is private unless you export it. Each module has a set of exported bindings. A binding is a name tied to a value, type, or namespace. Each binding is either a named export or the default export. Importers choose how to receive them:
- Named imports pick bindings by name.
- A default import receives the single default binding under any name you choose.
- A namespace import collects every named export into one object.
Named exports
A named export attaches a name to a declaration. You can export a function, class, variable, type alias, interface, or enum.
// shapes.ts
export interface Point {
x: number;
y: number;
}
export type Shape = "circle" | "square";
export const ORIGIN: Point = { x: 0, y: 0 };
export function distance(a: Point, b: Point): number {
return Math.hypot(a.x - b.x, a.y - b.y);
}You can also declare first and export later with an export list. This keeps all exports in one place, which some teams prefer for readability.
// shapes-list.ts
interface Point {
x: number;
y: number;
}
function distance(a: Point, b: Point): number {
return Math.hypot(a.x - b.x, a.y - b.y);
}
export { distance, distance as dist, type Point };Three things happen in that export list:
distanceis exported under its own name.distance as distexports the same function under a second name.type Pointmarks the export as type-only. The next chapter covers this in detail.
Importers must use the exported name, or rename it locally with as:
// use-shapes.ts
import { distance as dist, ORIGIN } from "./shapes.js";
import type { Point } from "./shapes.js";
const p: Point = { x: 3, y: 4 };
console.log(dist(ORIGIN, p)); // 5Default exports
A module can have at most one default export. It may be any expression, and a function or class declaration may be anonymous.
// math.ts
export function add(a: number, b: number): number {
return a + b;
}
export const PI = 3.14159;
export default function multiply(a: number, b: number): number {
return a * b;
}// main.ts
import multiply, { add, PI } from "./math.js";
import * as math from "./math.js";
console.log(add(1, 2), multiply(2, 3), PI, math.add(3, 4));The first import line combines a default import (multiply) and a named import list ({ add, PI }). The default name always comes first. The name multiply on the importing side is your choice. This works too:
import times from "./math.js";
console.log(times(2, 5)); // 10That freedom is the main cost of default exports. Two files can import the same function under different names, which makes searching and automated renaming harder. Named exports keep one name across the codebase, and editors can offer auto-import for them reliably. Many style guides prefer named exports for that reason. Defaults remain common where a framework expects them, such as a page component or a config file.
A default export is just a binding named default. These two lines are equivalent:
// both of these export the same thing
export { multiply as default };
export default multiply;The distinction matters for re-exports, covered below.
Namespace imports
import * as math from "./math.js" creates one object whose properties are the module's exports. It includes the default export as a property named default.
import * as math from "./math.js";
console.log(math.add(1, 2));
console.log(math.default(2, 3)); // the default export
console.log(math.PI);Use a namespace import when a module has many exports and you want to group them under a prefix, or when you want to avoid name clashes between two modules:
import * as geometry from "./shapes.js";
import * as stats from "./stats.js";
geometry.distance(geometry.ORIGIN, { x: 1, y: 1 });
stats.mean([1, 2, 3]);The namespace object is read-only. Assigning to math.PI is a compile error.
Imports are live, read-only bindings
An import is not a copy. It is a read-only view of the exporting module's binding, and it reflects later changes made inside that module.
// counter.ts
export let count = 0;
export function increment(): void {
count += 1;
}// counter-main.ts
import { count, increment } from "./counter.js";
console.log(count); // 0
increment();
console.log(count); // 1
count = 5; // error: cannot assign to 'count' because it is an importOnly the exporting module can change count, and it does so through functions like increment. This is true of real ES modules at runtime, and TypeScript enforces it at compile time. When TypeScript compiles to CommonJS, it emits code that preserves the same behavior for exported let bindings.
Side-effect imports
An import with no bindings runs the module's top-level code and imports nothing:
import "./setup-env.js";TypeScript does not check that the file exports anything. Use this for polyfills, global registration, or module augmentation, which a later chapter covers.
Re-exporting
A module can forward exports from another module. This is how an index.ts file builds a single public entry point.
// index.ts
export { add, PI } from "./math.js";
export { default as multiply } from "./math.js";
export * from "./shapes.js";
export * as stats from "./stats.js";Each line does something different:
| Statement | Effect |
|---|---|
| `export { add, PI } from "./math.js"` | Forwards the listed named exports. |
| `export { default as multiply } from "./math.js"` | Forwards the default export under a new name. |
| `export * from "./shapes.js"` | Forwards every named export, but not the default. |
| `export * as stats from "./stats.js"` | Exposes the whole module as one namespace export called `stats`. |
export * never forwards a default export. If you want the default, you must name it explicitly as shown on the second line. If two export * statements provide the same name, TypeScript reports an ambiguity error rather than picking one.
Re-exporting does not create a local binding. After export { add } from "./math.js", the name add is not usable inside index.ts. Import it separately if you need it there.
The file extension in relative paths
When module is node16 or nodenext and the file is treated as an ES module, relative import paths must include the extension that will exist at runtime. You write ./math.js even though the source file is math.ts. TypeScript maps .js back to .ts when it looks for types, and the emitted JavaScript keeps the specifier unchanged so Node.js can load it.
import { add } from "./math.js"; // correct under nodenext ESM
import { add } from "./math"; // error in an ES module under nodenextUnder moduleResolution: "bundler" or older CommonJS-style settings, extensionless paths are accepted. A later chapter explains how those settings differ.
Common errors
- "Module has no exported member" (TS2305). You wrote
import { Add } from "./math.js"but the export isadd. Names are case-sensitive. - "Module has no default export" (TS1192). You wrote
import multiply from "./other.js"but that file only has named exports. Either add a default export or use braces. - "Cannot find module" (TS2307). The path is wrong, the extension is missing under nodenext, or the package has no types.
- Braces mismatch.
import add from "./math.js"gets the default export, which ismultiplyin the example, notadd. The code compiles, butaddis now the wrong function. Because the type is also a function of two numbers, TypeScript will not warn you.
Putting it together
Choose the form from what you need:
- Use named imports when you want specific bindings and a stable name across files.
- Use a default import when the module is built around one main value and its author provided a default.
- Use a namespace import to group a module's exports under one prefix or to avoid collisions.
- Use a side-effect import when you need the module to run and nothing else.
- Use re-exports to build a single public entry point without importing values you do not use locally.
Exercise
A file util.ts contains export function trim(s: string): string { return s.trim(); } and export default function shout(s: string): string { return s.toUpperCase(); }. Write one import line that gives you shout and trim in a file under module: nodenext. Then write a re-export line in index.ts that forwards shout under the name loud.
Show answer
import shout, { trim } from "./util.js"; and export { default as loud } from "./util.js";. The default comes first, the named import list follows in braces, and the path ends in .js. Using export * from "./util.js" would not work for the second part, because it never forwards a default export.
Exercise
In counter.ts, count is exported with export let count = 0;. Another module runs import { count } from "./counter.js" and then count = 10;. What happens, and what is the correct way to change the value?
Show answer
The assignment is a compile error, because an imported binding is read-only. The correct approach is to export a function from counter.ts, such as increment or setCount, that changes count inside the module. Importers then see the new value through their live binding.