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.
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}`;
}import describe, { area, PI } from "./math"; // default + named
import type { Shape } from "./math"; // type-only import, erased completely
import * as math from "./math"; // namespace import
const s: Shape = { kind: "circle", r: 2 };
console.log(describe(s), area(2), math.PI === PI);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.
utils.ts has export function slugify() {} and nothing else. Which import works?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.
export declare function formatBytes(bytes: number, decimals?: number): string;Packages get types in one of three ways:
- Bundled: the package is written in TypeScript or ships its own
.d.ts(Zod, Prisma, Next.js, Vite). Nothing to install. - DefinitelyTyped: a community repository of types for packages that do not ship them, published as
@types/<name>. - 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 typesYou also write .d.ts files to describe things that are not TypeScript at all, like image imports in a bundler or global variables:
declare module "*.svg" {
const src: string;
export default src;
}
declare global {
interface Window {
analytics?: { track(event: string): void };
}
}
export {};- 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.
{
"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"]
}| Option | What it does |
|---|---|
target | Which JavaScript version to emit and which built-ins exist. ES2022 is safe for current browsers and Node. |
lib | Which type definitions are available (DOM for browser APIs). |
module | The module syntax to emit. ESNext (or preserve) when a bundler handles it. |
moduleResolution | How import "x" is found. bundler matches Vite/Next.js. Use nodenext for code Node runs directly. |
strict | Turns on the whole strict family, including strictNullChecks and noImplicitAny. Always on. |
noUncheckedIndexedAccess | arr[i] and record[key] include undefined, because the index might not exist. |
isolatedModules | Forbids patterns a single-file transpiler cannot handle. Required for esbuild and SWC. |
skipLibCheck | Do not type-check .d.ts files in node_modules. Faster builds, fewer errors you cannot fix. |
noEmit | Only check; another tool produces the JavaScript. |
paths | Import aliases, so @/lib/api means ./src/lib/api. |
noUncheckedIndexedAccess is not part of strict, but it catches a very common bug:
Press Run (⌘ Enter) to see what happens.Without the flag, third is typed number, and third.toFixed(2) would compile and then crash.
"paths": { "@/*": ["./src/*"] } to tsconfig. The editor is happy, but running the compiled output with plain node fails with "Cannot find module '@/lib/api'". Why?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.
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.
{
"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: ... }'.Press Run (⌘ Enter) to see what happens.Use satisfies for config objects, route tables and lookup maps: you get validation and exact keys.
Put the steps for adding TypeScript checking to an existing Vite project in order.
- Tap the steps below in the right order.
Match the symptom to the option.
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. Returnnullif nothing matches.
resolveAlias("@/lib/utils", { "@/*": ["./src/*"] }) → "./src/lib/utils"
resolveAlias("react", { "@/*": ["./src/*"] }) → null- ES module
- A file with
import/export. Has its own scope and shares only what it exports. - declaration file
- A
.d.tsfile 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.