Publishing a typed library

Advanced · 21 min

Ship declaration files with your package, wire them up through package.json exports with types first, and check the result with Are the Types Wrong.

Before thisDeclaration files and DefinitelyTypedModule resolution

JavaScript Conferences by GitNation · 21 min

Publishing a typed library

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by JavaScript Conferences by GitNationReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Consumers never see your `.ts` source. Their compiler reads the `.d.ts` files you publish, found by following your `package.json` with the consumer's own module resolution settings.
  • `declaration: true` makes `tsc` emit a `.d.ts` beside each `.js` file, and `declarationMap: true` adds maps so go-to-definition in a consumer's editor lands in your source instead of the declaration.
  • The `exports` field defines the entry points of a modern package. Inside each entry, the `types` condition must come first, because conditions match in order and the first match wins.
  • Shipping both ESM and CommonJS doubles the surface for mistakes. Each format needs its own declaration file with a matching extension, and an app can end up loading two copies of your code. ESM-only is now a reasonable default.
  • `@arethetypeswrong/cli` resolves your packed tarball the way Node, bundlers, and older TypeScript settings would, and reports the mismatches that type-check fine in your own repo but break for users.

Your users never see your source

When someone installs your library, their compiler doesn’t read your .ts files. It reads the JavaScript you published and the declaration (.d.ts) files that describe it. It finds those by walking your package.json with their tsconfig, which may use a different module resolution mode from yours. A library can type-check perfectly in its own repo and still hand users missing types, any, or errors about default imports. Nearly every typed-library bug lives at this boundary.

Think of it like shipping a part with a spec sheet. The part is the JavaScript, the spec sheet is the .d.ts, and package.json is the label that tells the customer where each one is in the box. If the label is wrong, a perfect part still doesn’t fit.

How the compiler consumes .d.ts files is covered in declaration files and DefinitelyTyped. This lesson is the producer side.

Emitting declarations

Two options in the library’s tsconfig produce the spec sheets:

{
  "compilerOptions": {
    "target": "es2022",
    "module": "nodenext",
    "strict": true,
    "rootDir": "src",
    "outDir": "dist",
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true
  },
  "include": ["src"]
}

For this source:

// src/index.ts
export type Result<T, E = Error> =
  | { ok: true; value: T }
  | { ok: false; error: E };

export function ok<T>(value: T): Result<T, never> {
  return { ok: true, value };
}

tsc writes dist/index.js and dist/index.d.ts, which keeps the types and drops the bodies:

export type Result<T, E = Error> = {
    ok: true;
    value: T;
} | {
    ok: false;
    error: E;
};
export declare function ok<T>(value: T): Result<T, never>;
//# sourceMappingURL=index.d.ts.map

declarationMap adds index.d.ts.map, so when a user hits go-to-definition on ok, their editor opens your real source instead of the bare declaration. That only works if you publish src too.

Pointing at the types: exports

The exports field lists the entry points a package allows and maps each one to files using conditions. The simplest correct setup is ESM-only:

{
  "name": "tiny-result",
  "version": "1.0.0",
  "type": "module",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "default": "./dist/index.js"
    }
  },
  "files": ["dist", "src"]
}

The order inside that object matters. Conditions are tried top to bottom and the first match wins. TypeScript understands types, and it also matches import, require, and default. Put default first and TypeScript stops there, then looks for a declaration file next to index.js. That works by accident when the two sit side by side and breaks the day they don’t. types always goes first.

exports also seals the package: any path not listed can’t be imported. That’s usually what you want, since users can no longer reach into dist/internal/ and depend on it. Older tools that predate exports read the top-level main and types fields instead, so some libraries keep those as a fallback.

One more trap: if your public types mention another package’s types, such as Buffer from @types/node, that package belongs in dependencies or peerDependencies. Users don’t install your devDependencies.

Dual ESM and CommonJS

Plenty of libraries ship both formats so require users aren’t left out:

{
  "type": "module",
  "exports": {
    ".": {
      "import": { "types": "./dist/index.d.ts", "default": "./dist/index.js" },
      "require": { "types": "./dist/index.d.cts", "default": "./dist/index.cjs" }
    }
  }
}

Each branch has its own types, and that’s deliberate. TypeScript decides whether a declaration file describes ESM or CommonJS the same way Node decides for JavaScript: by extension, then by the nearest package.json "type". Reusing one index.d.ts for the CommonJS build means TypeScript believes the CommonJS code is ESM. The declaration is “masquerading”, and users get wrong default-import behavior. The CommonJS build needs a .d.cts.

There’s also the dual package hazard: an app whose dependencies load your package through both import and require gets two separate copies. Module-level state is duplicated and instanceof checks fail across the copies.

Producing both formats with matching declarations from plain tsc takes two configs and some care, which is why bundlers such as tsup and tsdown exist. Before taking that on, ask whether you need CommonJS at all. Node 20.19 and 22.12 onward can require() an ES module, so ESM-only packages now work for most CommonJS users too.

Checking the result

Your own repo won’t reveal any of this, because it compiles from source under one resolution mode. Check what users will receive:

npm pack --dry-run                    # which files actually ship
npx @arethetypeswrong/cli --pack .    # resolve the tarball under every mode

Are the Types Wrong packs the library and resolves each entry point the way Node from CommonJS, Node from ESM, a bundler, and older TypeScript settings would. It prints a table of problems such as “Resolution failed”, “Masquerading as ESM”, or “No types”. Run it in CI before every publish. publint is a useful companion that lints the package.json itself.

What the video covers

Mark Erikson maintains Redux and has fought every problem above across several widely used packages. His talk covers ESM versus CommonJS, the exports field and its types conditions, moduleResolution: node16, build output formats, and checking packages with Are the Types Wrong. It is a talk, not a step-by-step tutorial, and dates from 2023. The model it describes, exports plus types conditions checked with attw, is still the current one. What has shifted since is the case for dual builds, which require(esm) support in Node has weakened. For a hands-on build, the 2025 video and the tsdown introduction in the links show the tooling side.

Check yourself

  1. 01Why must `types` be listed before `default` inside an `exports` entry?

    Conditions are tried in the order written and the first one that matches wins. TypeScript matches `default` too, so if it comes first, TypeScript stops there and never reads your `types` path. It then only finds declarations if they happen to sit next to the JavaScript file.

  2. 02What is a "masquerading" declaration file in a dual ESM/CJS package?

    A declaration file whose module format doesn't match the JavaScript it describes, such as one `index.d.ts` in a `"type": "module"` package also serving the CommonJS build. TypeScript reads it as ESM, so CommonJS consumers get wrong answers about default imports and interop. The fix is a separate `.d.cts` for the CommonJS output.

  3. 03Your public function returns a type from `@types/node`, which is in `devDependencies`. What goes wrong for users?

    Dev dependencies are not installed for consumers, so your published `.d.ts` imports a package that isn't there. Users get an error, or with `skipLibCheck` on, the type quietly becomes `any`. A type your public API exposes belongs in `dependencies` or `peerDependencies`.

  4. 04Why run Are the Types Wrong on a packed tarball instead of trusting a clean `tsc` run in the library's repo?

    Your repo compiles the library with one module resolution mode from source. Users resolve the published package through `exports` under whatever settings they use, such as `node16` from CommonJS, `node16` from ESM, or `bundler`. Only checking the packed files under each mode shows what users actually get.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark