Sub topic 10
Dependencies, peer dependencies and @types packages in public types
This chapter assumes you can read a .d.ts file and know what npm install puts in node_modules. You should also know the earlier chapters' setup: tsc emits declaration files into dist, and exports points consumers at them. Here the question is which packages your consumers must have installed for your declaration files to type-check.
Why public types create dependencies
Your JavaScript output and your declaration files have different dependency footprints. A package used only inside a function body shows up in dist/*.js and nowhere in dist/*.d.ts. A package whose types appear in a signature, an exported interface, or a base class is copied into the .d.ts as an import.
Consider a function that accepts a Node stream:
// src/slugStream.ts
import type { Readable } from "node:stream";
export async function slugifyStream(input: Readable): Promise<string> {
const chunks: Buffer[] = [];
for await (const chunk of input) {
chunks.push(Buffer.from(chunk));
}
return Buffer.concat(chunks).toString("utf8").trim().toLowerCase();
}tsc emits this declaration:
// dist/slugStream.d.ts
import type { Readable } from "node:stream";
export declare function slugifyStream(input: Readable): Promise<string>;The import of node:stream is now part of your public contract. The consumer's compiler reads dist/slugStream.d.ts, follows that import, and needs the types for node:stream. Those come from @types/node. If the consumer doesn't have it, the compiler cannot resolve the module.
What the consumer sees when a type is missing
Without skipLibCheck, the consumer gets an error inside your declaration file:
node_modules/@acme/slugify/dist/slugStream.d.ts:1:31 - error TS2307: Cannot find module 'node:stream' or its corresponding type declarations.Most application projects enable skipLibCheck, so the error disappears. The problem doesn't. The unresolved Readable silently becomes any, so the parameter accepts anything and the consumer loses checking with no warning. This is why you can't treat "no complaints" as proof that your dependencies are right.
Sorting a dependency into the right field
Every package your declarations import falls into one of three categories. Decide per package, not per project.
| Situation | Field | Reason |
|---|---|---|
| Used only in compiled JavaScript, absent from `.d.ts` | `dependencies` | Needed at runtime. Consumers never need its types. |
| Used only for building or testing | `devDependencies` | Consumers never install it. |
| Appears in public types and the consumer is expected to have their own copy | `peerDependencies` | One shared copy, so types from your package and the consumer's code are identical. |
| Appears in public types and the consumer doesn't normally install it | `dependencies` | You make sure the types arrive with your package. |
A package that is both used at runtime and exposed in types can go in either dependencies or peerDependencies. The deciding factor is whether the consumer's code and your code must share one instance.
Peer dependencies for shared identity
Suppose your library accepts a schema from zod and returns a value typed by it:
// src/parse.ts
import type { ZodType, infer as ZodInfer } from "zod";
export function parseWith<S extends ZodType>(schema: S, value: unknown): ZodInfer<S> {
return schema.parse(value);
}If you list zod in dependencies, a consumer on [email protected] may end up with a second copy, [email protected], nested under your package. TypeScript treats classes with private members or unique symbols from two copies as different types. The consumer then sees confusing errors where a schema they built "is not assignable" to the parameter. A peer dependency avoids this because the package manager uses the consumer's single copy.
{
"name": "@acme/slugify",
"peerDependencies": {
"zod": "^3.22.0"
},
"devDependencies": {
"zod": "^3.23.8",
"typescript": "^5.6.0"
}
}Note that zod appears twice. The peer entry tells consumers what range works. The dev entry installs a copy so that you can compile and test locally. Peer dependencies are not installed into your own project for development in every setup, so keep the devDependencies entry.
Use a wide range in peerDependencies. A narrow range such as 3.23.8 makes installs fail for anyone on another version. Widen it only to versions you have actually tested.
Optional peers
If only part of your API uses the type, mark the peer optional so that consumers who never touch that part are not warned:
{
"peerDependencies": {
"zod": "^3.22.0"
},
"peerDependenciesMeta": {
"zod": {
"optional": true
}
}
}An optional peer fixes the install warning but not the type problem. A consumer who skips zod still gets an unresolved import in parse.d.ts. If that file is reachable from your main entry point, the any problem returns. Put optional-peer APIs behind a subpath export, such as @acme/slugify/zod, so the file is only loaded by people who installed the peer.
@types packages
Many JavaScript packages ship no types of their own. Their types live in a separate @types/* package from DefinitelyTyped. If your declarations import from such a package, two things must be installed for the consumer: the package itself, and its @types companion.
Take a library that exposes Express middleware:
// src/middleware.ts
import type { Request, Response, NextFunction } from "express";
export function slugParam(req: Request, _res: Response, next: NextFunction): void {
req.params.slug = String(req.params.slug ?? "").toLowerCase();
next();
}Consumers of this middleware already have express, so it is a peer. They may not have @types/express, especially in a plain JavaScript project that merely wants editor hints. You have three options.
- Peer dependency on
@types/express. Consumers install it themselves. It matches their Express version and avoids duplicates. The cost is an extra install step for them. - Regular dependency on
@types/express. It always arrives. The risk is a second copy of the types when the consumer pins a different version, which causes the same mismatch errors as duplicate runtime packages. - Remove the type from your public surface. Define a small structural interface instead:
// src/middleware.ts
export interface ParamsRequest {
params: Record<string, string | undefined>;
}
export function slugParam(req: ParamsRequest, _res: unknown, next: () => void): void {
req.params.slug = String(req.params.slug ?? "").toLowerCase();
next();
}Express's Request satisfies ParamsRequest, so callers don't notice the change. This option has no type dependency and no version conflicts. It works whenever you only need a few members of the foreign type.
Global types and @types/node
Buffer, process and NodeJS.ProcessEnv are globals from @types/node. They create the same problem without any visible import. Check your dist/*.d.ts for them. When the compiler emits a /// <reference types="node" /> line, your declarations depend on @types/node.
The same options apply. Libraries meant only for Node usually list @types/node as a peer or regular dependency. Libraries that also run in browsers should keep Node types out of their public signatures, for example by accepting Uint8Array instead of Buffer.
Finding what your declarations import
Don't rely on memory. List every bare package name imported from your built declarations:
npm run build
grep -rhoE 'from "[^"./][^"]*"' dist --include="*.d.ts" | sort -u
grep -rn 'reference types=' dist --include="*.d.ts"The first command prints entries such as from "zod" and from "node:stream". Every package name on that list must appear in dependencies or peerDependencies, and a package that has a separate @types companion needs that companion handled too. Names that appear only in devDependencies are bugs. They work on your machine and break on every consumer's.
Verifying with a clean consumer
The check that settles the question is a test project with a fresh node_modules and skipLibCheck set to false:
{
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"skipLibCheck": false,
"noEmit": true
},
"include": ["index.ts"]
}Install only the tarball from npm pack and the dependencies a real consumer would add, then run tsc. If your declarations reference something that isn't installed, the compiler reports TS2307. Add the package to the right field and repeat.
Common mistakes
- Putting a package in
devDependenciesbecause "it's only types". If consumers' compilers must resolve it, it is not a dev-only package. - Listing
@types/*independenciesfor a package that is only used inside function bodies. Those types never reach your declarations, so you are installing them for nothing. - Using exact peer versions. Use ranges that cover what you tested.
- Forgetting
import type. WithverbatimModuleSyntaxorisolatedModules, a type-only import written as a normal import can leave a runtimeimportin your JavaScript. Then a package you meant as types-only becomes a runtime requirement.
Exercise
Your library exports function render(el: HTMLElement, store: Store): void, where Store is imported from the redux package in your declarations. redux ships its own types. Which field should redux go in, what other field should also list it, and how do you confirm the choice is right?
Show answer
Because Store appears in public types and consumers almost certainly use their own copy of redux (two copies would produce mismatched Store types), put redux in peerDependencies with a wide tested range, such as ^4.2.0 || ^5.0.0. Also list it in devDependencies so you can compile and test locally. No @types package is needed because redux bundles its types. To confirm, build, run the grep for from "..." in dist/*.d.ts to see that redux is listed, then install the packed tarball into a test consumer with skipLibCheck: false and run tsc. The consumer should compile with redux installed and should report TS2307 if it is removed.