Sub topic 6
How TypeScript finds types for a module
This chapter assumes you know what an import specifier is and how nodenext and bundler differ at a high level. It also assumes you can read a package.json with main, type, and exports fields. It covers the second half of every resolution: after TypeScript finds a file for an import, where does it get the types?
Two questions, one lookup
When the compiler sees import { x } from "some-module", it needs a file it can read types from. That file is not always the file Node.js would run. At runtime Node.js loads a .js file. At compile time TypeScript prefers a file with type information, in this order:
- A TypeScript source file (
.ts,.tsx,.mts,.cts). - A declaration file (
.d.ts,.d.mts,.d.cts). - A JavaScript file (
.js,.mjs,.cjs), only ifallowJsis on.
If the lookup ends at a plain JavaScript file and allowJs is off, TypeScript reports error TS7016: "Could not find a declaration file for module". The import resolved. It just has no types.
A declaration file is a file that contains only type information, with no runnable code. The compiler uses it to check your code, and it never emits it as JavaScript.
Relative imports: the extension swap
For a relative import, TypeScript takes the written specifier and tries the matching TypeScript-side files. Under nodenext, you write the runtime extension, and the compiler maps it back to the source extension.
| Specifier ends in | TypeScript tries, in order |
|---|---|
| `./greet.js` | `greet.ts`, `greet.tsx`, `greet.d.ts` |
| `./greet.mjs` | `greet.mts`, `greet.d.mts` |
| `./greet.cjs` | `greet.cts`, `greet.d.cts` |
This is why the import in an ES module file says ./greet.js even though only greet.ts exists on disk. After compilation, greet.js really will exist, and the specifier is already correct for Node.js.
// src/main.ts, in a package whose package.json has "type": "module"
import { greet } from "./greet.js";
console.log(greet("world"));Under bundler resolution, extensionless relative imports such as ./greet also work. TypeScript then tries greet.ts, greet.tsx, greet.d.ts, and then a directory with an index file.
Bare specifiers: looking in node_modules
A bare specifier is a name with no leading ./ or /, such as lodash or @scope/pkg. TypeScript walks up from the importing file's directory, checking each node_modules folder along the way, as Node.js does. In each folder it checks two places for a package named pkg, in this order:
node_modules/pkg, the package itself, looking for its own types.node_modules/@types/pkg, the community-maintained declarations from DefinitelyTyped.
The package's own types win over @types. If the package ships types and you also install @types/pkg, the @types copy is ignored for that import. Installing @types/pkg for a package that bundles its own types is a common but harmless mistake.
Scoped packages follow a naming rule for @types. The package @scope/pkg has its declarations in @types/scope__pkg, with a double underscore replacing the slash.
Inside the package
Once TypeScript is inside node_modules/pkg, it reads package.json and decides which file to use. The order depends on the resolution mode.
With nodenext and bundler, if the package has an exports field, TypeScript uses it and ignores types, typings, and main. The exports field is the single source of truth. You can see the mechanism in this map, which selects different declaration files for import and require:
{
"name": "example-lib",
"type": "module",
"exports": {
".": {
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
}
}
}Conditions are checked in the order they appear in the object, and the first matching one wins. TypeScript always matches types, so it must come before default. If default is listed first, TypeScript takes the JavaScript file and never reaches the declarations.
When there is no exports field, TypeScript falls back to the older fields:
typesVersions, if present, which can redirect paths based on the TypeScript version.typesortypings, pointing straight at a.d.tsfile.main, with its extension swapped for a declaration extension. Amainoflib/index.jsmakes TypeScript trylib/index.ts, thenlib/index.d.ts.- A file named
indexat the package root, such asindex.d.ts.
{
"name": "old-style-lib",
"version": "1.0.0",
"main": "./lib/index.js",
"types": "./lib/index.d.ts"
}The lookup as a flow
Declaration files carry a module format too
Under nodenext, a declaration file has a format just like a source file. A .d.ts file takes its format from the nearest package.json type field: ESM if it says "module", CommonJS otherwise. A .d.mts file is always ESM, and a .d.cts file is always CommonJS.
This is why the example above ships two declaration files for one library. If dist/index.d.ts sits in a package with "type": "module", TypeScript treats its types as an ES module. A CommonJS consumer that requires the package would get types that describe the wrong module shape. The separate index.d.cts lets that consumer see CommonJS-shaped types. A single .d.ts file shared by both branches is a well-known source of subtle errors, such as a default export that TypeScript thinks is default.default at runtime.
Declaring types yourself
Sometimes no declaration file exists. You have three options, from least to most effort.
An ambient module declaration
An ambient declaration describes a module without implementing it. Put this in a .d.ts file that your tsconfig.json includes, for example src/types/untyped.d.ts:
declare module "untyped-lib" {
export function parse(input: string): { ok: boolean; value: string };
}The file must not contain a top-level import or export, or TypeScript treats it as a module and the declare module becomes an augmentation instead of a new declaration.
For a quick escape hatch, a shorthand declaration types everything from the module as any:
declare module "untyped-lib";Wildcard declarations for assets
Bundler setups often import non-code files. A wildcard pattern gives them a type:
declare module "*.svg" {
const url: string;
export default url;
}TypeScript only checks that the type exists. Your bundler must actually handle .svg files at build time.
typeRoots and types
By default, every folder under node_modules/@types is included as a global type package, and TypeScript loads it even if you never import it. Two options control this:
typeRootsreplaces the list of folders that are searched for global type packages.typesrestricts which packages from those folders are loaded automatically.
{
"compilerOptions": {
"module": "nodenext",
"types": ["node"]
}
}With "types": ["node"], only @types/node is auto-loaded as a global. This does not stop an explicit import from finding @types/lodash. It only limits what is loaded without an import. Setting "types": [] is a useful way to catch code that relies on a global such as describe without importing or configuring its types.
Gotchas
- TS7016 is not a resolution failure. The module was found. Add
@types/pkg, write an ambient declaration, or enableallowJsif appropriate. - TS2307 "Cannot find module" is a resolution failure. Check the specifier, the extension rules, and the
exportsmap. - A restrictive
exportsmap hides files. If a package exports only".", thenpkg/lib/utilfails to resolve even thoughnode_modules/pkg/lib/util.d.tsexists. skipLibCheckhides errors in declaration files, not in resolution. It stops TypeScript from type-checking.d.tsfiles. It does not change which file is chosen.- Types and runtime can disagree. TypeScript trusts the declaration file. If
exportspointstypesat a file that describes a different build thandefault, the compiler accepts code that crashes at runtime.
Seeing the lookup
To confirm which file TypeScript chose, trace one import:
npx tsc --noEmit --traceResolution | grep "untyped-lib"The output lists each candidate path in order and the final resolved file, or the reason for failing. Later chapters cover reading that output in detail.
Exercise
A package fancy-lib has "main": "./lib/index.js", no exports field, and lib/index.d.ts exists. You compile with moduleResolution: nodenext. Which file does TypeScript use for import "fancy-lib", and what changes if the package adds "exports": { ".": { "default": "./lib/index.js" } } without a types condition?
Show answer
Without exports, TypeScript takes main, swaps the extension, and finds lib/index.d.ts. After exports is added, TypeScript uses only the exports map. The default condition points at lib/index.js, and TypeScript looks for a declaration file next to it (lib/index.d.ts) using the extension swap, so it can still find types there, but main is no longer consulted. Adding an explicit types condition before default is the reliable way to state the declaration file.
Exercise
You install @types/chalk-like and also the package chalk-like, which ships its own index.d.ts. Which declarations does import "chalk-like" use, and why does a .d.ts file containing both declare module "x" { } and a top-level export const a = 1; not behave as an ambient module declaration?
Show answer
The package's own index.d.ts is used, because TypeScript checks node_modules/chalk-like before node_modules/@types/chalk-like. A top-level export makes the file a module, and inside a module declare module "x" is treated as an augmentation of an existing module x, not as a new ambient declaration. Ambient declarations need a file with no top-level import or export.