Sub topic 11
Using bundled types and @types packages
This chapter assumes you can run tsc, edit tsconfig.json, and use npm and package.json. You should also know how import and export work, and how the compiler turns an import specifier into a file. Here you learn where TypeScript finds types for a third-party package, and what to do when it finds none.
Two sources of types
A package written in JavaScript has no type information. TypeScript gets types for it in one of two ways.
- Bundled types. The package ships its own
.d.tsfiles and points to them frompackage.json. Installing the package installs the types. @typespackages. A separate package, published under the@typesscope on npm, holds declarations for a package that does not ship its own. These come from the DefinitelyTyped repository.
If neither exists, the import is an error (or an implicit any, depending on settings). The next chapter's tools, ambient declarations, cover that case. This chapter covers the first two.
Bundled types
When you import "zod" or "axios", TypeScript runs module resolution. It looks in node_modules/<name> and reads that package's package.json. It looks for a types entry in this order:
- The
exportsfield, if the resolution mode supports it (node16,nodenext,bundler). Thetypescondition is matched first. - The
typesfield (or its older aliastypings). - The
mainfield, with the extension swapped to.d.ts. - An
index.d.tsat the package root.
A package that bundles types usually has this in its package.json:
{
"name": "tiny-lib",
"version": "2.1.0",
"main": "./dist/index.js",
"types": "./dist/index.d.ts"
}You do nothing extra. The import is typed as soon as the package is installed:
import { parse } from "tiny-lib";
const result = parse("a=1");If you hover over parse in your editor, the signature comes from node_modules/tiny-lib/dist/index.d.ts.
@types packages
For a package without bundled types, install the matching @types package as a development dependency:
npm install lodash
npm install --save-dev @types/lodashThe runtime code lives in lodash. The types live in @types/lodash. The @types package contains only declarations, so you do not need it at runtime and it belongs in devDependencies.
The naming rule
The @types name is derived from the package name:
| Runtime package | Types package |
|---|---|
| `lodash` | `@types/lodash` |
| `express` | `@types/express` |
| `node:fs` and other Node built-ins | `@types/node` |
| `@babel/core` (scoped) | `@types/babel__core` |
Scoped packages replace the / with a double underscore. The built-in Node modules (fs, path, process) also need @types/node. Without it, import fs from "node:fs" fails with a "cannot find module" error.
How @types packages are found
TypeScript resolves import "lodash" by looking in node_modules/lodash first. If that folder has no types, it then checks node_modules/@types/lodash. You never write @types in an import.
The diagram below shows the lookup order.
Bundled types win when both are present, because the package is checked first. This matters when a package starts shipping its own types: the old @types package becomes unused and should be removed. Many @types packages are then marked deprecated on npm.
The `types` and `typeRoots` options
By default, TypeScript includes every visible package under node_modules/@types as a global declaration source, even if you never import it. This is how globals such as describe (from @types/jest) or process (from @types/node) become available without an import.
Two compiler options restrict that behavior.
typeslists exactly which@typespackages are included as globals.typeRootschanges which folders are scanned instead ofnode_modules/@types.
{
"compilerOptions": {
"module": "nodenext",
"strict": true,
"types": ["node"]
},
"include": ["src"]
}With "types": ["node"], only @types/node is loaded automatically. Globals from @types/jest disappear from the project, which is useful when test types would otherwise leak into production code.
Versions and compatibility
An @types package follows the version of the library it describes by major and minor number. @types/[email protected] describes [email protected]. The patch number is independent, because it tracks fixes to the declarations rather than to the library.
Match the major and minor version of the types to the library you run. A mismatch causes two kinds of error:
- Types that show APIs your installed version does not have, so code compiles but fails at runtime.
- Types that miss APIs your installed version does have, so valid code fails to compile.
You can check which versions are installed:
npm ls react @types/reactWhat bundled types look like in practice
Open a package's .d.ts file to see what you are consuming. Here is a small declaration file for a package that exports one function and one interface:
// node_modules/tiny-lib/dist/index.d.ts
export interface ParseOptions {
strict?: boolean;
}
export declare function parse(
input: string,
options?: ParseOptions
): Record<string, string>;Your code can import both names. The interface is erased at compile time, so use import type when you want to make that clear:
import { parse } from "tiny-lib";
import type { ParseOptions } from "tiny-lib";
const options: ParseOptions = { strict: true };
console.log(parse("a=1", options));Common errors
TS7016: could not find a declaration file
error TS7016: Could not find a declaration file for module 'some-lib'.
'/project/node_modules/some-lib/index.js' implicitly has an 'any' type.The package is present and has JavaScript, but no types. Under strict (which enables noImplicitAny) this is an error. Options, from best to worst:
- Install
@types/some-libif it exists. - Write your own
declare module "some-lib"declaration. - As a last resort, declare it with no body,
declare module "some-lib";. Every import then has typeany.
TS2307: cannot find module
This usually means the package is not installed, the name is misspelled, or moduleResolution cannot read the package's exports field. Check node_modules first, then your module setting.
Types found, but they disagree with the runtime
The @types version does not match the library version. Check both with npm ls and align them.
Duplicate or conflicting global types
Two @types packages can declare the same global, for example @types/jest and @types/mocha both declare describe. Use the types option, or split the project into separate tsconfig.json files for source and tests.
Decision guide
| Situation | Action |
|---|---|
| Package has a `types` field or `exports` types condition | Install it and import. No extra step. |
| Package has no types, `@types/<name>` exists | `npm install --save-dev @types/<name>` |
| Neither exists | Write an ambient declaration |
| Test globals leak into app code | Restrict with the `types` option |
| You use Node built-ins | Install `@types/node` |
Exercise
You install express and import it in a strict TypeScript project. The compiler reports TS7016 for "express". You then run npm install --save-dev @types/express and the error disappears. Why did the fix work, which dependency section is correct for it, and what would you check if types then disagreed with runtime behavior?
Show answer
express ships JavaScript only, so TypeScript found no bundled types in node_modules/express. It then looked in node_modules/@types/express, which the install created, and used those declarations. The package holds only types, so it belongs in devDependencies. If the types and runtime disagree, run npm ls express @types/express and align the major and minor versions of the two packages.
Exercise
A project's tsconfig.json sets "types": ["node"]. A test file calls describe(...) without an import, and @types/jest is installed. Does it compile, and how would you fix it?
Show answer
It fails, because types limits which @types packages are included as globals and jest is not listed. Add "jest" to types, or put test files under a separate tsconfig.json whose types includes "jest".