AI Hints
TypeScript · Lesson 73 of 120

Modules

Import and export.

⏱ 2 min read▶ Video at 56:06🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Real projects are split into many files, called modules. A module exports what others may use. Other files import it. And types travel along with the code.

Modules
From the video: Modules
  • Many files
  • export
  • import

pricing.ts

Pricing dot TS exports a constant, a function, and a type. Anything not exported stays private to the file.

pricing.tstypescript
export const VAT = 0.2;

export function withVat(price: number): number {
  return Math.round(price * (1 + VAT) * 100) / 100;
}

export type Money = { amount: number; currency: "GBP" | "EUR" };

Importing it

App dot TS imports the function and the type. With Node's module system, the import path ends in dot JS, because that's the file that will run. Run it.

app.tstypescript
import { withVat, type Money } from "./pricing.js";

const price: Money = { amount: withVat(849.5), currency: "GBP" };
console.log(price);
Output
{ amount: 1019.4, currency: 'GBP' }
Also uses pricing.ts
export const VAT = 0.2;

export function withVat(price: number): number {
  return Math.round(price * (1 + VAT) * 100) / 100;
}

export type Money = { amount: number; currency: "GBP" | "EUR" };

Summary

Export what others may use, and import it by path. Types travel with the code. Next, type only imports.

Key takeaways
  • export
  • import { x } from
  • ./file.js
Next up: Type-Only Imports — import type