Learn TypeScript Β· 14/14

Modules, Third-Party Libs, and Configuration

8 min read

Welcome back, Camper! πŸ•οΈ

So far, you’ve been writing TypeScript code that probably lives in a single file. That works great for a calculator function or a "Hello World" script. But imagine building an entire operating system or a social media clone in one file. You would end up with a 50,000-line file called main.ts. Trying to find a bug in that would be like trying to find a specific needle in a stack of identical needles while blindfolded.

Today, we graduate from writing scripts to building projects. We are going to learn how to split our code, configure the TypeScript compiler so it behaves exactly how we want, and use code written by other people without TypeScript yelling at us.

Let's organize the chaos! 🧹


1. ES Modules in TypeScript: Exporting and Importing

The Problem: The Global Scope Disaster

In the old days of JavaScript, everything was global. If you defined a variable user in fileA.js and another user in fileB.js, they would clash and overwrite each other. It was the Wild West.

The Solution: Modules

A Module is simply a file containing related code (variables, functions, classes). Crucially, variables inside a module are scoped to that file. They are invisible to the rest of the app unless you explicitly give permission to share them.

TypeScript uses the modern ES Module (ECMAScript Module) standard.

Exporting (The "Giver")

To make something available to other files, you use the keyword export.

Named Exports (Recommended):
This allows you to export multiple items from a file.

typescript
// utils.ts

// This function is visible outside
export function calculateTax(amount: number): number {
  return amount * 1.2;
}

// This constant is visible outside
export const APP_NAME = "ShopMaster v1";

// This is NOT exported. It is private to this file.
const SECRET_KEY = "123456"; 

Default Exports:
This is used when a file is primarily designed to export one main thing.

typescript
// Logger.ts
export default class Logger {
  log(msg: string) {
    console.log(msg);
  }
}

Industry Tip: πŸ—οΈ Many teams prefer Named Exports over Default Exports. Named exports force the file importing the code to use the exact same name, which makes renaming (refactoring) much easier across a large project.

Importing (The "Receiver")

To use the code, you import it.

Importing Named Exports:
The names must match exactly (unless you rename them using as).

typescript
// main.ts
import { calculateTax, APP_NAME } from "./utils";

console.log(APP_NAME); // "ShopMaster v1"
console.log(calculateTax(100)); // 120

Importing Default Exports:
You can name the import whatever you want.

typescript
// main.ts
import MySuperLogger from "./Logger"; // Name it whatever

const logger = new MySuperLogger();

Type-Only Imports

TypeScript has a unique feature called import type. Since TypeScript types disappear when compiled to JavaScript, you can explicitly tell the compiler, "Hey, I only need this for type checking, remove it completely from the final JavaScript."

typescript
// types.ts
export interface User {
  id: number;
  name: string;
}

// app.ts
import type { User } from "./types";

const newUser: User = { id: 1, name: "Alice" };

Why? It helps some bundlers (tools that package your code) run faster and avoid circular dependency issues.


2. Deep Dive into tsconfig.json: Strict Mode & Target

The Problem: Chaos Control

The TypeScript compiler (tsc) is powerful, but it needs instructions.

  • Should it treat your code as modern JavaScript or old Internet Explorer JavaScript?
  • Should it be super strict about errors or let you be lazy?
  • Where should it put the compiled files?

If you don't provide a config, tsc will try to guess, and computers are bad guessers.

The Solution: tsconfig.json

This file is the control panel for your project. You generate it by running:

bash
tsc --init

Let's look at the most critical settings inside the compilerOptions object.

1. target (Time Travel)

This tells TypeScript which version of JavaScript to output.

  • "target": "ES5": The compiler will translate your modern arrow functions and classes into old-school function syntax so it runs on very old browsers.
  • "target": "ESNext": The compiler keeps the code modern. It's cleaner and faster, but won't run on a browser from 2012.

Fun Fact: Setting the target to ES3 (from 1999) turns your beautiful modern code into an unrecognizable mess of helper functions, but it proves how powerful the transpiler is!

2. strict (God Mode)

This is actually a bundle of several checks. Setting "strict": true is the industry standard. It turns on:

  • noImplicitAny: You cannot leave a variable without a type if TS can't infer it. It bans the "magic" any unless you explicitly write it.
  • strictNullChecks: This is the big one. In non-strict mode, null and undefined are ignored. In strict mode, if a user can be null, TS forces you to check for it before using it.

Example without strictNullChecks (The Bug Factory):

typescript
function getLength(str: string | null) {
  return str.length; // CRASH if str is null! TS stays silent. πŸ’€
}

Example WITH strictNullChecks:

typescript
function getLength(str: string | null) {
  // TypeScript Error: Object is possibly 'null'.
  // You must fix it:
  if (str) {
    return str.length;
  }
  return 0;
}

3. outDir and rootDir

  • rootDir: Where your TypeScript source files live (usually ./src).
  • outDir: Where the compiled JavaScript files land (usually ./dist or ./build).

This keeps your project clean. You don't want .ts and .js files mixing in the same folder like dirty and clean laundry.


3. Working with Third-Party Libraries (@types and DefinitelyTyped)

The Problem: The "Silent" Library

You want to use Lodash (a famous JS utility library) or Express. You install it:
npm install lodash

You try to import it:

typescript
import _ from "lodash"; 
// Error: Could not find a declaration file for module 'lodash'. 
// '.../node_modules/lodash/lodash.js' implicitly has an 'any' type.

TypeScript is panicking. "I don't know what lodash is! Is it a number? A bird? A plane? I can't help you autocomplete code if I don't know the shape of this library!"

Most libraries are written in plain JavaScript, which has no type information.

The Solution: DefinitelyTyped (@types)

The TypeScript community is amazing. They have created a massive repository called DefinitelyTyped. It contains "Declaration Files" (.d.ts) for almost every JavaScript library in existence. These files act as a translator, telling TypeScript what types the JavaScript library expects.

How to fix it:

You install the types as a development dependency (since you only need types while coding, not running).

bash
npm install --save-dev @types/lodash

Poof! The error is gone. Now when you type _., VS Code will show you all the Lodash functions with their correct parameters.

What if there are no types?

Rarely, you might find a library that has no @types package. You have two options:

  1. Cry. (Not recommended).
  2. Create a generic definition file (e.g., declarations.d.ts) in your source folder:
typescript
// src/declarations.d.ts
declare module 'my-obscure-library';

This tells TypeScript: "Trust me, this module exists. Treat everything inside it as any and stop yelling."


4. Structuring a Standard TypeScript Project

The Problem: Spaghetti Folders

If you dump index.ts, utils.ts, config.json, README.md, and database.ts all in the root folder, your project becomes unnavigable.

The Solution: Standard Directory Layout

Here is the industry-standard structure for a backend or library project.

text
my-app/
β”œβ”€β”€ node_modules/       # Dependencies (never touch this)
β”œβ”€β”€ src/                # Your Logic Lives Here 🧠
β”‚   β”œβ”€β”€ index.ts        # Entry point
β”‚   β”œβ”€β”€ utils.ts
β”‚   └── models/         # Sub-folders for organization
β”œβ”€β”€ dist/               # Compiled JS (Generated by computer) πŸ€–
β”œβ”€β”€ test/               # Unit tests
β”œβ”€β”€ package.json        # Project manifest
β”œβ”€β”€ tsconfig.json       # TS Configuration
└── .gitignore          # Git ignore file

Step-by-Step Setup (Hands-On)

  1. Initialize Node Project:

    bash
    mkdir my-ts-app
    cd my-ts-app
    npm init -y
  2. Install TypeScript:

    bash
    npm install --save-dev typescript
  3. Generate Config:

    bash
    npx tsc --init
  4. Configure tsconfig.json:
    Open the file and uncomment/change these lines:

    json
    {
      "compilerOptions": {
        "target": "ES2020",
        "module": "commonjs",     // Use "NodeNext" or "ESNext" for modern Node
        "rootDir": "./src",
        "outDir": "./dist",
        "strict": true,
        "esModuleInterop": true   // Helps import CommonJS modules nicely
      }
    }
  5. Add Scripts:
    Update package.json to make running easy.

    json
    "scripts": {
      "build": "tsc",
      "start": "node dist/index.js",
      "dev": "tsc --watch"
    }
  6. Create .gitignore:
    You never want to commit your node_modules or the compiled dist folder to GitHub. The dist folder is derived data; it can always be regenerated from src.

    text
    node_modules
    dist

Now, you can write code in src/index.ts, run npm run build, and watch your organized, type-safe JavaScript appear in dist/.


πŸ“š References & Extra Reading

Now go forth and structure your code like a pro! πŸš€

Challenge

TypeScript Project Refactor

You have been given a snapshot of a broken TypeScript project contained within a single file. Your task is to fix the module resolution, handle a third-party library without types, and answer a conceptual question about compiler configuration.

Instructions:

  1. In the code section marked // file: src/cart.ts, correctly export the CartItem type and the calculateSubtotal function using named exports.
  2. In the code section marked // file: src/index.ts, import the CartItem type and calculateSubtotal function from ./cart.
  3. The project uses a fictional third-party library called uuid-generator, which is missing its type declarations. Below all the file blocks, write an ambient module declaration for 'uuid-generator' to eliminate the TypeScript error. The module should declare a default export that is a function returning a string.
  4. At the very end of the file, answer the multiple-choice question inside the comment block. Identify the tsconfig.json option responsible for catching potential null or undefined errors.

Expected result

The final code should be fully functional without any TypeScript errors.

  1. The src/cart.ts section should have export keywords before the type CartItem and const calculateSubtotal definitions.
  2. The src/index.ts section should begin with the line import { type CartItem, calculateSubtotal } from './cart';.
  3. A module declaration block should be present, similar to:
    typescript
    declare module 'uuid-generator' {
      const generateId: () => string;
      export default generateId;
    }
  4. The conceptual question should be answered correctly with B) strictNullChecks.
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.