Skip to content

Lesson 44 of 50TypeScript

Modules and tsconfig

Understand imports and exports, .d.ts files and @types, every important tsconfig option, and how TS fits in a build.

16 min read0/4 questions

Most "TypeScript is broken" moments on a real project have nothing to do with types. They are module and config problems: an import that resolves in the editor but not at runtime, a library with no types, a tsconfig.json copied from a blog post in 2019. This lesson is the map of how files, types and build tools fit together, so you can set up a project and debug it when it complains.

ES modules: import and export

Every file with a top-level import or export is a module with its own scope. You choose what to share.

export const PI = 3.14159;                 // named export
 
export function area(r: number): number {  // named export
  return PI * r * r;
}
 
export type Shape = { kind: "circle"; r: number }; // types can be exported too
 
export default function describe(s: Shape): string { // default export (one per file)
  return `circle of radius ${s.r}`;
}

Named exports are imported by their exact name, so a rename is caught everywhere and editors can auto-import them. A default export can be imported under any name, which makes it harder to search for. Many teams prefer named exports everywhere, except where a framework requires a default (Next.js page.tsx and layout.tsx files do).

import type tells the compiler the import is only used as a type, so it is guaranteed to vanish from the output. With the verbatimModuleSyntax option on, you must mark type-only imports this way, which keeps build tools from guessing.

Quick check
utils.ts has export function slugify() {} and nothing else. Which import works?
Need a nudge? A hint rules out a wrong answer.

CommonJS interop

Node.js had modules before JavaScript did. CommonJS uses require() and module.exports, and a lot of npm still ships it.

// CommonJS (older Node packages)
const express = require("express");
module.exports = { start };

TypeScript can import CommonJS packages with ES syntax. Because a CommonJS module has no real default, the esModuleInterop option makes import express from "express" work by treating module.exports as the default. It is on in every modern template, so you rarely think about it until an old package misbehaves.

For new code, write ES modules. In a Node project, "type": "module" in package.json makes .js files ES modules.

Declaration files and DefinitelyTyped

A declaration file (.d.ts) contains only types: no code. It describes JavaScript that lives somewhere else. When you import { z } from "zod", TypeScript reads the package's bundled .d.ts files.

node_modules/some-lib/index.d.ts
export declare function formatBytes(bytes: number, decimals?: number): string;

Packages get types in one of three ways:

  1. Bundled: the package is written in TypeScript or ships its own .d.ts (Zod, Prisma, Next.js, Vite). Nothing to install.
  2. DefinitelyTyped: a community repository of types for packages that do not ship them, published as @types/<name>.
  3. None: you write a small declaration yourself.
npm install --save-dev @types/node        # types for Node's built-in modulesnpm install --save-dev @types/express     # Express does not bundle its types

You also write .d.ts files to describe things that are not TypeScript at all, like image imports in a bundler or global variables:

src/types/assets.d.ts
declare module "*.svg" {
  const src: string;
  export default src;
}
 
declare global {
  interface Window {
    analytics?: { track(event: string): void };
  }
}
export {};
Where TypeScript finds types
  • my-app/
  • tsconfig.jsonwhich files, which rules
  • package.json
  • src/
  • main.ts
  • lib/
  • api.ts
  • types/
  • assets.d.tsyour own declarations
  • node_modules/
  • zod/
  • index.d.tsbundled types
  • @types/
  • node/DefinitelyTyped: types for Node built-ins
  • express/DefinitelyTyped: types for Express

tsconfig.json, explained

tsconfig.json marks the root of a TypeScript project and sets the compiler options. Here is a modern config for an app built with a bundler (Vite or Next.js), with every important line explained.

tsconfig.json
{
  "compilerOptions": {
    "target": "ES2022",
    "lib": ["ES2023", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "moduleResolution": "bundler",
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "isolatedModules": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "paths": { "@/*": ["./src/*"] }
  },
  "include": ["src"]
}
OptionWhat it does
targetWhich JavaScript version to emit and which built-ins exist. ES2022 is safe for current browsers and Node.
libWhich type definitions are available (DOM for browser APIs).
moduleThe module syntax to emit. ESNext (or preserve) when a bundler handles it.
moduleResolutionHow import "x" is found. bundler matches Vite/Next.js. Use nodenext for code Node runs directly.
strictTurns on the whole strict family, including strictNullChecks and noImplicitAny. Always on.
noUncheckedIndexedAccessarr[i] and record[key] include undefined, because the index might not exist.
isolatedModulesForbids patterns a single-file transpiler cannot handle. Required for esbuild and SWC.
skipLibCheckDo not type-check .d.ts files in node_modules. Faster builds, fewer errors you cannot fix.
noEmitOnly check; another tool produces the JavaScript.
pathsImport aliases, so @/lib/api means ./src/lib/api.

noUncheckedIndexedAccess is not part of strict, but it catches a very common bug:

TypeScript
const scores = [90, 72];const third = scores[2]; // with the flag: number | undefinedconsole.log(third); // undefined at runtime const prices: Record<string, number> = { apple: 120 };const pear = prices["pear"]; // with the flag: number | undefinedconsole.log(pear === undefined ? "no price" : pear.toFixed(2));
Output
Press Run (⌘ Enter) to see what happens.

Without the flag, third is typed number, and third.toFixed(2) would compile and then crash.

Quick check
You add "paths": { "@/*": ["./src/*"] } to tsconfig. The editor is happy, but running the compiled output with plain node fails with "Cannot find module '@/lib/api'". Why?
Need a nudge? A hint rules out a wrong answer.

How TypeScript fits in a real build

In modern projects, tsc usually does not produce the JavaScript. Fast tools strip types file by file, and tsc only checks.

Two jobs, two tools
src/*.ts: your codesrc/*.tsyour codeesbuild / SWC: strip types, fastesbuild / SWCstrip types, fastBundle: JS for the browserBundleJS for the browsertsc --noEmit: type check onlytsc --noEmittype check onlyCI: fails on errorsCIfails on errorsdev + buildemitcheckexit code

Vite (esbuild or Oxc) and Next.js (SWC) delete types without checking them. That is why saving a file reloads in milliseconds, even with type errors.

1/2
package.json
{
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "typecheck": "tsc --noEmit"
  }
}

This split is also why isolatedModules exists: a tool that sees one file at a time cannot know whether an imported name is a type (to delete) or a value (to keep). Type-only imports and isolatedModules remove the guesswork.

satisfies: check without widening

You first met satisfies with unions in Unions and Narrowing. Here is the general rule, which matters most for config files. Annotating a value with a type replaces its inferred type, which can lose detail. The satisfies operator (TypeScript 4.9) checks that a value matches a type but keeps the precise inferred type.

type Route = { path: string; auth: boolean };
 
const annotated: Record<string, Route> = {
  home: { path: "/", auth: false },
  settings: { path: "/settings", auth: true },
};
annotated.profile.path; // compiles (any string key allowed), crashes at runtime
 
const routes = {
  home: { path: "/", auth: false },
  settings: { path: "/settings", auth: true },
} satisfies Record<string, Route>;
 
routes.profile;
// Error: Property 'profile' does not exist on type '{ home: ...; settings: ... }'.
TypeScript
type Route = { path: string; auth: boolean }; const routes = { home: { path: "/", auth: false }, settings: { path: "/settings", auth: true },} satisfies Record<string, Route>; type RouteName = keyof typeof routes; // "home" | "settings" function link(name: RouteName): string { return routes[name].path;} console.log(link("settings"), Object.keys(routes).length);
Output
Press Run (⌘ Enter) to see what happens.

Use satisfies for config objects, route tables and lookup maps: you get validation and exact keys.

Put it in order5 steps

Put the steps for adding TypeScript checking to an existing Vite project in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Match the pairs0/5 matched

Match the symptom to the option.

Choose an item, then its match on the other side.
ChallengeMedium

Resolve a paths alias

In tsconfig.json, compilerOptions.paths maps import specifiers to folders:

{ "paths": { "@/*": ["./src/*"], "@ui/*": ["./src/components/ui/*"] } }

Write resolveAlias(specifier: string, paths: Record<string, string[]>): string | null, a tiny version of what the compiler does:

  • A pattern without * matches only that exact specifier. Exact matches win over wildcard ones.
  • A pattern with one * matches if the specifier starts with the part before * and ends with the part after it. The * captures what is in between.
  • If several wildcard patterns match, use the one with the longest prefix before the *.
  • Return the first target of the winning pattern, with its * replaced by the captured text. Return null if nothing matches.
resolveAlias("@/lib/utils", { "@/*": ["./src/*"] })   →  "./src/lib/utils"
resolveAlias("react", { "@/*": ["./src/*"] })         →  null
TypeScript
function resolveAlias( specifier: string, paths: Record<string, string[]>,): string | null { return null;}
Key terms
ES module
A file with import/export. Has its own scope and shares only what it exports.
declaration file
A .d.ts file containing only types that describe JavaScript defined elsewhere.
DefinitelyTyped
The community repository of types for untyped packages, installed as @types/<name>.
moduleResolution: bundler
Resolves imports the way Vite and Next.js do. The right choice for bundled apps.
tsc --noEmit
Type-checks the project without writing any files. The usual CI check when a bundler emits the JS.
satisfies
Checks a value against a type while keeping its precise inferred type.