Publishing typed packages
Relay customers want a client: createClient({ baseUrl, token, fetch }).enqueue("email.send", payload) instead of
hand-written fetch calls. You publish it as @relay/client. A consumer installs it, imports it, and expects
the editor to know that enqueue takes a kind and a payload and returns a Job.
A package has two audiences. The runtime wants JavaScript. The compiler wants declarations. The package has to
carry both, and its package.json has to say which file is for whom. A mistake here doesn’t show in your own
tests, which import the source. It shows in a customer’s project as any, or as Cannot find module.
Two outputs from one source
Section titled “Two outputs from one source”Bun makes the JavaScript, and tsc makes the declarations. Bun strips types and never writes .d.ts files:
bun build main.ts errors.ts --outdir dist --target node --splittingtsc -p tsconfig.build.jsonThe second command uses a config dedicated to the build, so it does not depend on the app’s settings:
{ "compilerOptions": { "target": "esnext", "module": "esnext", "moduleResolution": "bundler", "strict": true, "verbatimModuleSyntax": true, "allowImportingTsExtensions": true, "skipLibCheck": true, "declaration": true, "emitDeclarationOnly": true, "declarationMap": true, "isolatedDeclarations": true, "rootDir": ".", "outDir": "dist/types" }, "files": ["main.ts", "errors.ts"]}declaration writes .d.ts files. emitDeclarationOnly stops tsc from writing JavaScript, since Bun did
that. declarationMap writes a .d.ts.map next to each file. Both flags and --isolatedDeclarations work in the
tsc used by this course (TypeScript 7). The output for Relay’s main.ts is the public surface and nothing else, with
no function bodies:
export { RelayError } from "./errors.ts";export interface Job { readonly id: string; readonly kind: string;}export declare function createClient(options: RelayClientOptions): RelayClient;export declare const defaultTimeoutMs: number;export declare const retryDelays: readonly number[];//# sourceMappingURL=main.d.ts.mapThe map file records which .ts lines each declaration came from. In an editor, “go to definition” on createClient
then opens main.ts and not the .d.ts. The map’s sources is a relative path (../../main.ts here), so it only
helps where that source exists: a monorepo, or a package that ships its source.
isolatedDeclarations
Section titled “isolatedDeclarations”M5’s performance lesson introduced the flag as a speed tool. For a package it is also a safety
net. Without it, tsc infers a type from a function body to write the .d.ts, so a body change can alter your
public API without anyone meaning to. With it, every exported function, constant and class member must carry its
own type, and the compiler rejects the ones that do not:
export const defaultTimeoutMs = 30 * 1000export const retryDelays = [100, 200, 400]main.ts(41,14): error TS9010: Variable must have an explicit type annotation with --isolatedDeclarations.main.ts(42,28): error TS9017: Only const arrays can be inferred with --isolatedDeclarations.The fix is the annotation, and it is also the contract: defaultTimeoutMs: number, retryDelays: readonly number[].
The bug this prevents: retryDelays inferred as number[] would let a consumer push onto the SDK’s shared array.
The exports map
Section titled “The exports map”exports is the package’s public door. It lists the entry points, and nothing outside it can be imported (a
deep import such as @relay/client/dist/errors.js is Cannot find module). Each entry can be a bare path or an object of
conditions chosen by the tool that is importing:
{ "name": "@relay/client", "type": "module", "files": ["dist"], "exports": { ".": { "types": "./dist/types/main.d.ts", "default": "./dist/main.js" }, "./errors": { "types": "./dist/types/errors.d.ts", "default": "./dist/errors.js" } }}tsc asks for the types condition. Bun and Node take default. So each entry is a pair, and a bare string such as
"./errors": "./dist/errors.js" gives the runtime a file. The declarations are in dist/types, not next to the
JavaScript, so TypeScript finds none:
use.ts(1,28): error TS7016: Could not find a declaration file for module '@relay/client/errors'.Order matters
Section titled “Order matters”Conditions are tried in the order written, and the first one that resolves to a file wins. Put types first.
When default comes first, tsc follows it to ./dist/main.js and looks for a declaration file next to it. If one
is there, even a stale one from an older build, that file is used and the types entry you wrote is never read.
With a stale dist/main.d.ts next to main.js, the consumer was typed by the old file, and the error it reported
was about the old signature. When nothing is next to the JavaScript, tsc moves on to the next condition, so the
mistake can stay hidden until a build layout changes.
The other fields
Section titled “The other fields”typesandmainat the top level are the fallback for tools that ignoreexports. Set them to the same files as the"."entry. They cost two lines.typesVersionsis the legacy way to map subpaths such as@relay/client/errorsfor old resolvers:"typesVersions": { "*": { "errors": ["./dist/types/errors.d.ts"] } }. TypeScript ignores it whenever it readsexports, so it only matters for packages withoutexportsor for old resolvers such asnode10, which TypeScript 7 has removed (error TS5108: Option 'moduleResolution=node10' has been removed). Add it only if you must support consumers on old TypeScript.fileslists what is published.["dist"]keeps source, tests and config out of the package. Withoutfiles, everything not git-ignored goes in.
One copy of each class
Section titled “One copy of each class”main.ts re-exports RelayError from errors.ts, and both are entry points. Build them as two bundles and each
bundle gets its own copy of the class:
bun build main.ts errors.ts --outdir out --target node # class RelayError appears in main.js and errors.jsbun build main.ts errors.ts --outdir out --target node --splitting # one copy, in a shared chunkWith two copies, error instanceof RelayError is false when the error was thrown through the other entry point.
A consumer’s catch block would silently miss every SDK error. --splitting moves the shared code to a chunk both
entries import. The exercise’s test imports RelayError from both entries and checks they are the same class.
Exercise
Section titled “Exercise”Copy these files into a new folder in the Relay project, such as packages/client/, with package.starter.json
renamed to package.json and main.starter.ts to main.ts. errors.ts and tsconfig.build.json don’t change. Then run
bun test.
The package is broken in several ways, and you fix it in two files. package.json has a wrong main, a types
condition in the wrong place, a bare-string entry, no files, and a build script that never runs tsc. main.ts has
exports that isolatedDeclarations rejects. The test copies the package to a temp folder, runs your build script
there, installs the result into a small consumer project, and type-checks and runs that consumer. Run
bun run build yourself to see the errors in your own terminal. Your project needs typescript installed.
{ "name": "@relay/client", "version": "1.0.0", "type": "module", "main": "./src/main.js", "exports": { ".": { "default": "./dist/main.js", "types": "./dist/types/main.d.ts" }, "./errors": "./dist/errors.js" }, "scripts": { "build": "bun build main.ts errors.ts --outdir dist --target node" }}// Relay's client SDK is published as @relay/client. Its declarations are emitted with// `tsc -p tsconfig.build.json`, which turns on isolatedDeclarations (lesson 6 of M5):// every export must say its type without the compiler reading function bodies.//// Rules:// - Every exported function and constant has an explicit type, so the declaration emit succeeds.// - Keep the types: createClient returns a RelayClient, defaultTimeoutMs is a number,// retryDelays is a readonly array of numbers.import { RelayError } from "./errors.ts"
export { RelayError } from "./errors.ts"
export interface Job { readonly id: string readonly kind: string}
export interface FetchResponse { readonly ok: boolean readonly status: number json(): Promise<unknown>}
export type FetchLike = ( url: string, init: { method: string; headers: Record<string, string>; body?: string }) => Promise<FetchResponse>
export interface RelayClientOptions { readonly baseUrl: string readonly token: string readonly fetch: FetchLike}
export interface RelayClient { enqueue(kind: string, payload: unknown): Promise<Job> get(id: string): Promise<Job>}
export const defaultTimeoutMs = 30 * 1000export const retryDelays = [100, 200, 400]
function toJob(value: unknown): Job { if (typeof value === "object" && value !== null && "id" in value && "kind" in value) { const { id, kind } = value if (typeof id === "string" && typeof kind === "string") return { id, kind } } throw new RelayError("malformed job", 502)}
export function createClient(options: RelayClientOptions) { async function call(method: string, path: string, body?: string): Promise<Job> { const res = await options.fetch(options.baseUrl + path, { method, headers: { authorization: `Bearer ${options.token}`, "content-type": "application/json" }, ...(body === undefined ? {} : { body }) }) if (!res.ok) throw new RelayError(`relay answered ${res.status}`, res.status) return toJob(await res.json()) }
return { enqueue: (kind: string, payload: unknown) => call("POST", "/jobs", JSON.stringify({ kind, payload })), get: (id: string) => call("GET", `/jobs/${id}`) }}export class RelayError extends Error { readonly status: number
constructor(message: string, status: number) { super(message) this.name = "RelayError" this.status = status }}import { afterAll, beforeAll, expect, test } from "bun:test"import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"import { tmpdir } from "node:os"import { dirname, join } from "node:path"
const tsc = [join(import.meta.dir, "../../../node_modules/.bin/tsc"), join(process.cwd(), "node_modules/.bin/tsc")].find(existsSync) ?? "tsc"
const pkgDir = mkdtempSync(join(tmpdir(), "relay-pkg-"))const consumer = join(pkgDir, "consumer")let build = { code: -1, out: "" }
function run(cmd: string[], cwd: string, env: Record<string, string | undefined> = process.env): { code: number; out: string } { const r = Bun.spawnSync(cmd, { cwd, env }) return { code: r.exitCode, out: r.stdout.toString() + r.stderr.toString() }}
function readPackage(): { files?: string[]; main?: string; types?: string; exports?: Record<string, unknown>; scripts?: Record<string, string> } { return JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf8"))}
beforeAll(() => { for (const f of ["main.ts", "errors.ts", "package.json", "tsconfig.build.json"]) { cpSync(join(import.meta.dir, f), join(pkgDir, f)) } mkdirSync(join(pkgDir, "bin")) symlinkSync(tsc, join(pkgDir, "bin/tsc")) build = run([process.execPath, "run", "build"], pkgDir, { ...process.env, PATH: `${join(pkgDir, "bin")}:${process.env.PATH}` })
mkdirSync(join(consumer, "node_modules/@relay"), { recursive: true }) symlinkSync(pkgDir, join(consumer, "node_modules/@relay/client")) writeFileSync(join(consumer, "package.json"), '{ "type": "module" }') writeFileSync( join(consumer, "use.ts"), `import { createClient, RelayError, type Job } from "@relay/client"import { RelayError as SameError } from "@relay/client/errors"
export const client = createClient({ baseUrl: "https://relay.example.com", token: "t", fetch: async () => ({ ok: true, status: 200, json: async () => ({ id: "job_1", kind: "email.send" }) })})export const job: Promise<Job> = client.enqueue("email.send", { to: "ops@example.com" })export const error: RelayError = new SameError("x", 500)
// @ts-expect-error: token is requiredcreateClient({ baseUrl: "https://relay.example.com", fetch: async () => ({ ok: true, status: 200, json: async () => ({}) }) })// @ts-expect-error: the error status is a numberexport const status: string = error.status` ) writeFileSync( join(consumer, "run.ts"), `import { createClient, RelayError } from "@relay/client"import { RelayError as SameError } from "@relay/client/errors"
const ok = createClient({ baseUrl: "https://r", token: "t", fetch: async () => ({ ok: true, status: 200, json: async () => ({ id: "job_1", kind: "email.send" }) }) })const down = createClient({ baseUrl: "https://r", token: "t", fetch: async () => ({ ok: false, status: 503, json: async () => ({}) }) })const job = await ok.enqueue("email.send", {})const failure = await down.get("job_1").catch((e: unknown) => e)console.log(JSON.stringify({ job, sameClass: RelayError === SameError, isRelayError: failure instanceof SameError }))` )})
afterAll(() => rmSync(pkgDir, { recursive: true, force: true }))
test("the package builds: JavaScript with bun, declarations with tsc", () => { expect(build.out).not.toContain("error TS") expect(build.code).toBe(0) expect(existsSync(join(pkgDir, "dist/main.js"))).toBe(true) expect(existsSync(join(pkgDir, "dist/types/main.d.ts"))).toBe(true)})
test("declaration maps are emitted next to the declarations", () => { expect(existsSync(join(pkgDir, "dist/types/main.d.ts.map"))).toBe(true)})
test("every exports entry puts `types` before the runtime conditions", () => { const exportsMap = readPackage().exports expect(exportsMap).toBeDefined() for (const [subpath, entry] of Object.entries(exportsMap ?? {})) { if (typeof entry !== "object" || entry === null) { throw new Error(`"${subpath}" is a bare string: add a conditions object with a "types" entry`) } expect(Object.keys(entry)[0]).toBe("types") }})
test("every file named by `exports`, `main` and `types` exists after the build", () => { const pkg = readPackage() const targets: string[] = [] for (const entry of Object.values(pkg.exports ?? {})) { if (typeof entry === "object" && entry !== null) { for (const target of Object.values(entry)) if (typeof target === "string") targets.push(target) } } if (pkg.main !== undefined) targets.push(pkg.main) if (pkg.types !== undefined) targets.push(pkg.types) expect(targets.length).toBeGreaterThanOrEqual(5) for (const t of targets) expect([t, existsSync(join(pkgDir, t))]).toEqual([t, true])})
test("`files` publishes dist only", () => { expect(readPackage().files).toEqual(["dist"])})
test("a consumer type-checks against the package with bundler and nodenext resolution", () => { for (const mode of [["--module", "esnext", "--moduleResolution", "bundler"], ["--module", "nodenext"]]) { const r = run([tsc, "--noEmit", "--strict", "--target", "esnext", ...mode, "--ignoreConfig", "use.ts"], consumer) expect(r.out).toBe("") expect(r.code).toBe(0) }})
test("the built JavaScript runs, and RelayError is one class across entry points", () => { const r = run([process.execPath, "run.ts"], consumer) expect(r.code).toBe(0) expect(JSON.parse(r.out)).toEqual({ job: { id: "job_1", kind: "email.send" }, sameClass: true, isRelayError: true })})- Bun builds the JavaScript,
tsc --declaration --emitDeclarationOnlybuilds the declarations, anddeclarationMaplets the editor jump to source. isolatedDeclarationsmakes every exported type explicit, so the public API changes only when you change it.exportsis the public door. Each entry is{ "types": ..., "default": ... }, withtypesfirst.- Keep
typesandmainas a fallback,typesVersionsonly for old consumers, andfiles: ["dist"]. - With several entry points, build with
--splitting, orinstanceofbreaks across them.
Further reading
Section titled “Further reading”- TypeScript handbook: Modules reference, package.json exports: subpaths and conditions such as types.
- TypeScript handbook: Modules reference, typesVersions: the legacy mapping.
- TypeScript 5.5 release notes: isolated declarations: why exports need explicit types.
- TypeScript handbook: Publishing declaration files: bundling types and the types field.