Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~6 min readTypeScript
#TypeScript#Declaration Files#pnpm#Build
A declaration sheet whose import arrow points into nested package boxes and ends at an amber empty slot

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:

  1. 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.
  2. 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.
  3. 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.

bash
# 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
ts
// 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:

ts
// 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

DiagnosticMessage coreUsual triggerFix shape
TS2742inferred type cannot be named without a referencetype anchored in a nested dependencyannotate the export
TS4023using name from external module but cannot be nameda type exists only inside a dependencyre-export the type
TS4094property of exported anonymous class may not be privateanonymous class exported as a valuename the class
TS9006declaration emit for this file requires using private nameisolatedDeclarations projectexport or annotate the name
FixEffortPublic API effectWorks with pnpm store
Explicit return type on the exportlowmakes the contract visibleyes
Re-export the dependency typelowadds a public type exportyes
Wrap in a local interfacemediumdecouples from the libraryyes
Hoist node_modules (npm or yarn)mediumnonenot applicable
skipLibCheck truenonenone, error staysno
EnvironmentWhy the reference is unreachableNote
pnpmpackages live in a content-addressed store, symlinked into node_modulesthe emitted relative path is meaningless to consumers
npm with nested versionstwo copies of @types/node at different depthsTypeScript picks the one it resolved
monorepo workspacestypes come through a sibling package's dependencythe sibling is not a dependency of the consumer
Yarn PnPno node_modules at allthere 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:

ts
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:

ts
// 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.

ini
# .npmrc - a workaround for a legacy repo, not a design node-linker=hoisted

If 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:

ts
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:

bash
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 inferred

Diffing 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.ts files; 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 --noEmit covers you. Type checking and declaration emit are separate passes; a green tsc --noEmit says nothing about portability.
  • Ignoring the error until publish. Emit may still produce a .d.ts with 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 --build checks; 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; use NodeNext for 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 documentation

The TypeScript documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.

All TypeScript guides

More in TypeScript

All TypeScript guides

The guides filed next to this one in TypeScript, in library order.