TypeScriptLesson 14 of 16

Modules and namespaces: organising code

In a real project every file is a module: you export what others need and import it where it is used. This lesson runs in one file, so a plain object plays the module.

Key points

  • A file with import or export is a module with its own scope.
  • export function format() {...} in one file, import { format } from "./money" in another.
  • import type brings in types only, and the line vanishes after compiling.
  • namespace predates ES modules; it is not deprecated, but TypeScript recommends modules for new code.
  • Running .ts directly in Node.js and the erasableSyntaxOnly flag reject namespaces, just like enums.

Example

// In a real project every file is a module:////   // money.ts//   export type Currency = "USD" | "EUR";//   export function format(amount: number, currency: Currency): string { ... }////   // main.ts//   import { format } from "./money";//   import type { Currency } from "./money"; // type-only, erased after compiling//// The lesson runs in one file, so a plain object plays the role of the module.type Currency = "USD" | "EUR"; const money = {  format(amount: number, currency: Currency): string {    return `${amount.toFixed(2)} ${currency}`;  },  add(a: number, b: number): number {    return Math.round((a + b) * 100) / 100;  },}; console.log(money.format(money.add(0.1, 0.2), "EUR"));

The comment shows how money would look as two files. The money object groups related functions under one name, exactly as a module would.

Task

How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.

Rewrite namespace Temperature as a plain temperature object, add a toCelsius method and print four lines: "0C = 32F", "25C = 77F", "100C = 212F", "212F = 100C".

Output

What your program prints appears here.