TS2742: the inferred type cannot be named without a reference
Type checking passes and only declaration emit fails. Annotate the exported boundary so consumers can resolve the emitted type.

Introduction & Quick Summary
Building a library or a composite project with declaration: true fails with error TS2742: The inferred type of 'createClient' cannot be named without a reference to '../node_modules/@types/pg'. This is likely not portable. A type annotation is necessary. The code is correct, the types resolve in the editor, and tsc --noEmit passes. Only the declaration emit fails.
The error means TypeScript computed a type for an exported symbol that it can express only by naming a module your emitted .d.ts cannot reach. Declaration files are self-contained contracts: they can import from what the consumer can resolve, not from your private node_modules layout. When the inferred type is anchored in a nested dependency - a second copy of @types/node, a pnpm-symlinked package, a type reached through typeof on a library value - the emit cannot write a portable import for it.
Three ways out, in order of preference:
- Annotate the export. Write the public type explicitly, importing it from a package you actually depend on. The error disappears because the type is now named by your own code.
- Re-export the type and use it.
export type { Pool } from "pg"plus an explicit return annotation makes the contract part of your public API instead of an inferred accident. - Simplify the inferred expression. Replace
ReturnType<typeof drizzle>or a deep generic chain with a named interface at the boundary.
What does not work: skipLibCheck, adding the dependency as a dev dependency only, or hoisting node_modules and hoping. Those change the symptom sometimes and the portability problem never.
Core Mechanics, Signatures & Reproducible Setup
Declaration emit has to serialize every exported symbol's type into text. For a type that comes from a module, that text is an import("specifier").Name node, and the specifier must be resolvable from the .d.ts file's location by the consumer. When TypeScript can name the type only through a path that is not reachable from the output - typically a nested node_modules, a symlinked store, or a type that exists only through an ambient augmentation - it reports TS2742 instead of emitting a fragile import.
# minimal setup that reproduces it
npm init -y
npm i -D typescript@5.9.3
npm i postgres
cat > tsconfig.json <<'JSON'
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"declaration": true,
"emitDeclarationOnly": true,
"outDir": "dist",
"strict": true
},
"include": ["src"]
}
JSON// src/db.ts
import postgres from "postgres";
export const sql = postgres(process.env.DATABASE_URL!); // infers a deep generic type
// src/repo.ts
import { sql } from "./db";
export const findUser = async (id: string) => {
return sql`select id, email from users where id = ${id}`;
// TS2742 can surface here: the inferred type references postgres internals
};The two companion diagnostics come from the same emitter and usually appear together:
// TS4023: exported variable 'client' has or is using name 'PoolConfig'
// from external module "pg" but cannot be named.
export const client = makePool();
// TS4094: Property 'secret' of exported anonymous class type may not be
// private or protected.
export const instance = new (class {
private secret = 1;
})();For a library, isolatedDeclarations (TypeScript 5.5+) makes this class of problem explicit: every exported symbol must have an annotation that a single-file transpiler can emit without type inference. Turning it on forces the same discipline this error asks for, one file at a time, instead of failing late on a type that only a full program can compute.
Key Comparison Table
| Diagnostic | Message core | Usual trigger | Fix shape |
|---|---|---|---|
| TS2742 | inferred type cannot be named without a reference | type anchored in a nested dependency | annotate the export |
| TS4023 | using name from external module but cannot be named | a type exists only inside a dependency | re-export the type |
| TS4094 | property of exported anonymous class may not be private | anonymous class exported as a value | name the class |
| TS9006 | declaration emit for this file requires using private name | isolatedDeclarations project | export or annotate the name |
| Fix | Effort | Public API effect | Works with pnpm store |
|---|---|---|---|
| Explicit return type on the export | low | makes the contract visible | yes |
| Re-export the dependency type | low | adds a public type export | yes |
| Wrap in a local interface | medium | decouples from the library | yes |
| Hoist node_modules (npm or yarn) | medium | none | not applicable |
| skipLibCheck true | none | none, error stays | no |
| Environment | Why the reference is unreachable | Note |
|---|---|---|
| pnpm | packages live in a content-addressed store, symlinked into node_modules | the emitted relative path is meaningless to consumers |
| npm with nested versions | two copies of @types/node at different depths | TypeScript picks the one it resolved |
| monorepo workspaces | types come through a sibling package's dependency | the sibling is not a dependency of the consumer |
| Yarn PnP | no node_modules at all | there is no path to write |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Annotate the boundary, not every function
Only exported symbols need portable types. A common mistake is annotating every helper until the code is unreadable. Annotate where the type leaves the module:
import type { Sql } from "postgres";
export function createSql(url: string): Sql {
return postgres(url);
}import type is erased at runtime, so the emitted declaration contains an import that the consumer resolves from the dependency you already list in peerDependencies or dependencies.
2. Make the dependency type part of your public API
When your function returns a library object, the honest declaration says so. Re-export the type and keep one import path for consumers:
// src/index.ts
export type { Pool, PoolClient } from "pg";
import type { Pool } from "pg";
export function getPool(connectionString: string): Pool {
return new Pool({ connectionString });
}Add the package to dependencies (or peerDependencies with a wide range for a plugin) so the consumer can resolve the import. A type-only import still needs the package present at type-check time.
3. pnpm: why hoisting is not the fix
With the default symlinked layout, TypeScript resolves a package through the project's virtual store, and the reference it records points into .pnpm. Even when emit succeeds, the .d.ts can contain a path a consumer cannot resolve. The supported answers are the two above; node-linker=hoisted changes the layout for the whole workspace and only hides the class of bug.
# .npmrc - a workaround for a legacy repo, not a design
node-linker=hoistedIf you inherit a repo that needs it, keep the annotation fixes in place as well, because a future migration off hoisting will bring the error back.
4. Generic factories and inferred return types
A generic factory that returns a function with an inferred type often cannot be named. Give the factory an explicit signature and the emitter has something to write:
type Handler<T> = (input: T) => Promise<void>;
export function defineHandler<T>(fn: Handler<T>): Handler<T> {
return fn;
}The same applies to ReturnType<typeof schema.parse>: annotate the domain type instead, so generated code does not leak a library's internal generic into your contract.
5. Composite projects and incremental builds
In a project referenced by others, composite: true implies declaration: true, so the error can appear in a package that never intended to publish types. Either give the package a public type surface or stop exporting the offending value:
{
"compilerOptions": {
"composite": true,
"declaration": true,
"declarationMap": true,
"isolatedDeclarations": true
}
}declarationMap helps consumers jump to your source but does nothing for TS2742; the missing piece is the named type.
6. Reading the emitted output to confirm the fix
After annotating, inspect what actually ships. A clean declaration should import only from your package or from declared dependencies:
rm -rf dist && npx tsc -p tsconfig.json
grep -R "import(" dist --include=*.d.ts | head
# any reference into ../../node_modules means the boundary is still inferredDiffing the previous and current dist/*.d.ts output in Text Diff makes the change obvious: one import line added, one deep reference gone. When two builds of the same package must be compared, that diff is the fastest way to see which boundary is still inferred.
Common Compilation/Runtime Mistakes & Version Gotchas
- Reaching for
skipLibCheck: true. It suppresses errors inside.d.tsfiles; TS2742 is raised about your own source during emit. - Adding
@types/...as a dev dependency. The emitter needs the type resolvable for consumers too; type-only imports still resolve at the consumer's type-check time. - Assuming
--noEmitcovers you. Type checking and declaration emit are separate passes; a greentsc --noEmitsays nothing about portability. - Ignoring the error until publish. Emit may still produce a
.d.tswith an unreachable import; consumers then fail with "cannot find module" inside your published types, which is harder to diagnose than the original error. - TypeScript version drift. TS 5.5 added
isolatedDeclarations, TS 5.6 tightened--buildchecks; a compiler upgrade can start failing emit with no source change. moduleResolution: "bundler"in a library. It permits resolution paths that Node consumers cannot follow; useNodeNextfor anything published to npm.- Exporting a class expression with private members. TS4094 replaces TS2742; name the class and export the name.
Primary references: the declaration option in tsconfig documents the emit rules and its interaction with composite and isolatedDeclarations, and Publishing declaration files describes what a consumer must be able to resolve from your package.
Official references
primary documentationThe TypeScript documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related TypeScript guides
All TypeScript guidesTS1294: This syntax is not allowed when erasableSyntaxOnly is enabled
Enums, namespaces and parameter properties emit code, so erasable mode rejects them. Convert each to an erasable form without changing call sites.
ESLint 9: the flat config error and why .eslintrc stopped loading
Flat config is one array, one root file, and no string extends. Here is the conversion, the four settings with no equivalent, and the editor trap.
TypeScript 7 native tsc: moduleResolution, baseUrl and API errors
The native compiler changes three defaults and drops the compiler API. Fix tsconfig first, then alias TypeScript 6 for eslint and ts-node.
TypeScript TS2769: No overload matches this call
Every overload rejected an argument. Read the failing signature, fix the one incompatible property, and know when a cast is honest.
More in TypeScript
All TypeScript guidesThe guides filed next to this one in TypeScript, in library order.