← Learning Hub
Intermediate

Modules and tsconfig.json

Real projects are many files that import and export from each other, and tsconfig.json tells the compiler how to treat them. Turning on strict mode from day one catches the most bugs, especially around null and undefined.

import and export

Each file is a module. Export what other files need, and import it there. Types can be exported too.

Example
// money.ts
export type Rupees = number;
export function formatINR(n: Rupees): string {
  return "Rs " + n.toLocaleString("en-IN");
}

// app.ts
import { formatINR, type Rupees } from "./money.js";
const total: Rupees = 125000;
console.log(formatINR(total));

tsconfig.json

A tsconfig.json file holds the compiler settings for the project. Create one with npx tsc --init, then run just npx tsc.

Example
{
  "compilerOptions": {
    "target": "ES2022",          // which JavaScript version to output
    "module": "NodeNext",        // how imports work (for Node.js)
    "outDir": "dist",            // where the .js files go
    "rootDir": "src",
    "strict": true,              // turn on all the important checks
    "noUncheckedIndexedAccess": true,
    "skipLibCheck": true
  },
  "include": ["src"]
}

What strict mode catches

Example
You can edit this code.

Types for libraries

Many npm packages ship their own types. For older ones, install the types from DefinitelyTyped: npm install -D @types/express. Node.js itself needs @types/node.

Always keep "strict": true in new projects. Turning it on later in a big project is much harder.
Key points
  • import and export share code (and types) between files.
  • tsconfig.json holds compiler settings.
  • Always use "strict": true.

📝 Test yourself

1. Which file holds the TypeScript settings for a project?
2. What does "strict": true do?
3. Fill in the package that adds Node.js types:
npm install -D @types/