Module 29: Modules, Classes, Generics and Utility Types
Modules, import and export
🏠The everyday picture
A book split into chapters. Each chapter covers one subject, refers to others by name ("see Chapter 4"), and can be read and revised on its own.
📘What it really is
- A module is a file that shares some of its contents with other files and keeps the rest private.
- Export what other files may use:
// bill.ts
export function lineTotal(price: number, qty: number): number {
return price * qty;
}
- Import it where it's needed:
// app.ts
import { lineTotal } from "./bill.ts";
import type { Product } from "./types.ts";
import type brings in types only; they disappear when the code runs.
-
These are ES modules, the modern standard in browsers and Node.js. Add
"type": "module"topackage.jsonto use them in Node.js. The olderrequireandmodule.exportsyou used in Module 26 (CommonJS) still appear in much existing code and AI answers; recognise it, but preferimport/exportfor new code. -
For running
.tsfiles directly with Node.js, imports include the.tsextension, and two settings intsconfig.jsonkeep things compatible:"allowImportingTsExtensions": trueand"verbatimModuleSyntax": true. -
Anything not exported stays private to its file, which keeps helper functions from being misused elsewhere.
🖱️Try it
Add "type": "module" to package.json and the two tsconfig.json settings above. Move your types into
types.ts, bill functions into bill.ts, data into data.ts, and keep only the "run the program" code in
app.ts, joined by imports. Run node app.ts and npm run check.
✅Quick check
A helper function in bill.ts isn't exported. Can app.ts use it?
Show the answer
No. Only exported things can be imported; the rest is private to the file.
What's the difference between import and import type?
Show the answer
import type brings in only types, which are removed when the code runs; import brings in real values.
