When Your Types Break Users but Your Code Does Not

A familiar story: a library ships a patch release with no runtime change at all, only "improved types", and a number of downstream builds go red overnight. The JavaScript still works. The TypeScript compiler, however, now refuses code that compiled yesterday. For users, that is a breaking change, whatever the runtime behaviour says.

Declarations are an API too

If you publish type declarations, whether written by hand or generated from TypeScript sources, those .d.ts files are part of what your users compile against. A user's build depends on them as much as on your function signatures. So I apply semantic versioning to declarations as well: if valid consumer code stops type-checking, that is a breaking change.

The tricky part is that type changes break in more subtle ways than runtime changes. Making a type more accurate can be the very thing that breaks people.

Common ways declarations break consumers

Notice that widening a parameter and narrowing a return are generally safe for callers, while the opposite directions are not. If users implement your interfaces rather than just call them, though, the safe directions flip, which is one reason to be clear about which types are meant to be implemented.

Catching type changes before release

I use two techniques. The first is a small set of type tests: files of consumer-style code that must compile, and a few that must not, checked in CI. In plain TypeScript, the @ts-expect-error comment makes the negative cases easy:

import { getUser } from "../dist/index.js";

const u = getUser("abc");
u.name.toUpperCase();          // must compile

// @ts-expect-error  numbers are not accepted
getUser(42);

The second is comparing the generated declaration output between the last release and the current branch. A diff of the .d.ts files in a pull request makes accidental changes visible to reviewers, who often never look at declarations otherwise. The post on snapshotting the public API describes a broader version of the same idea.

What about the supported compiler range?

I write down which TypeScript versions the declarations are tested with, and test the oldest one in CI. Some packages use the typesVersions field in package.json to serve different declarations to different compiler versions; it works, but adds maintenance, so I only reach for it when necessary. Whatever you choose, put the policy in the README so that raising the minimum is an announced decision, not a surprise.

← Back to Home

Subscribe to Our Newsletter

Get the latest updates delivered to your inbox.