Skip to content

Reading real .d.ts files

Relay’s router needs property tests, and the rules it matches form a tree: and, or and not hold other rules. You need random trees that stay small, and you have never used fc.letrec. The docs are one search away, but the declaration file in node_modules is always right for the version you installed, it is already on your disk, and the editor shows it on hover. Reading it is a skill, and this lesson gives it a method.

  1. Find the entry. Open the package’s package.json and follow exports (then types) to the file the compiler reads.
  2. Follow the re-exports. The entry is often a list of export { ... } from lines, or one big file with the exports at the bottom.
  3. Read overloads top to bottom. Each signature is a way to call the function, and the first that fits wins.
  4. Read the generics and constraints. <Ts extends [unknown, ...unknown[]]> says what the caller may pass, and what is inferred.
  5. Read the JSDoc. @default, @example, @remarks Since and @deprecated often say more than the types.
  6. Check by compiling. Write a call, then write one that should fail. The compiler confirms what you read.

fast-check’s package.json has this, abridged:

{
"exports": {
".": {
"import": {
"types@<5.7": "./lib/types57/fast-check.d.ts",
"types": "./lib/fast-check.d.ts",
"default": "./lib/fast-check.js"
}
}
}
}

import is for ESM, and types is the declaration. Lesson 4 said conditions are tried in order. Here is an order that matters: types@<5.7 is a version condition, so TypeScript before 5.7 reads a different, older declaration file, and newer ones skip it. The file to open is lib/fast-check.d.ts.

That one file holds the entire public API, about five thousand lines. Search it for the name you want, like function letrec. Not every function is written export declare. Some are plain declare function and are exported by a list at the very bottom, in the form export { ..., oneof, property, record, ... }, and in the same list fc as default, which is why import fc from "fast-check" works. For @types/bun the chain is the same but longer: @types/bun/index.d.ts is one line, /// <reference types="bun-types" />, and bun-types/index.d.ts references about twenty files. Bun.serve is in serve.d.ts.

fc.property has one signature, with a generic and a variadic tuple (M4 lesson 7):

declare function property<Ts extends [unknown, ...unknown[]]>(
...args: [...arbitraries: { [K in keyof Ts]: Arbitrary<Ts[K]> }, predicate: (...args: Ts) => boolean | void]
): IPropertyWithHooks<Ts>

Read it as a puzzle. Ts is the tuple of values the predicate receives. The arguments are one arbitrary per element of Ts, then the predicate. The compiler infers Ts from the arbitraries, so the predicate’s parameters are typed for free, and there are no overloads for “one arbitrary”, “two arbitraries” and so on. boolean | void means the predicate can return false or throw to fail, or return nothing and let expect calls do the work.

import fc from "fast-check"
const jobArb = fc.record({ id: fc.string({ minLength: 1 }), attempts: fc.nat(5) })
// Ts = [{ id: string; attempts: number }, boolean]
export const prop = fc.property(jobArb, fc.boolean(), (job, urgent) => job.attempts >= 0 || urgent)
fc.assert(prop)

fc.record has a generic and a second parameter:

declare function record<T, K extends keyof T = keyof T>(
model: { [K in keyof T]: Arbitrary<T[K]> },
constraints?: RecordConstraints<K>
): Arbitrary<RecordValue<T, K>>

T is inferred from the model. K is the set of keys that are always present, and it defaults to all of them. The return type RecordValue<T, K> is, a few lines up in the file, Prettify<Partial<T> & Pick<T, K & keyof T>>: the keys in K are required and the others optional. So requiredKeys changes the type, not just the data. Check what you read:

import fc from "fast-check"
type ValueOf<A> = A extends fc.Arbitrary<infer T> ? T : never
const arb = fc.record({ id: fc.string(), note: fc.string() }, { requiredKeys: ["id"] })
export const ok: ValueOf<typeof arb> = { id: "job_1" }
// @ts-expect-error: id is required by requiredKeys
export const missing: ValueOf<typeof arb> = { note: "x" }

The declarations carry documentation, and some of it is the only place a rule is written. Three kinds to look for:

  • @default gives the value you get if you pass nothing. In bun-types, maxRequestBodySize has @default 1024 * 1024 * 128, 128 MB. For Relay’s webhook endpoint that is far too large, and you would not know it from the type number | undefined.
  • @example shows a call that compiles against these very types. Copy it first.
  • @deprecated marks a name that still works. In fast-check, the timeout option of fc.assert says @deprecated Prefer the timeout plugin: fc.assert(property, { plugins: [fc.timeout(timeMs)] }).

tsc accepts a deprecated name without a message. Only the editor shows it, struck through, so you have to read the doc or look at the hover. A grep of @deprecated in the declaration file tells you which names to avoid before you write them.

Search serve.d.ts for function serve. The end of the file has the signature:

function serve<WebSocketData = undefined, R extends string = never>(
options: Serve.Options<WebSocketData, R>
): Server<WebSocketData>

R is the union of route paths. Follow Serve.Options and you get XOR<HostnamePortServeOptions, UnixServeOptions> & XOR<FetchOrRoutes, FetchOrRoutesWithWebSocket>. XOR<A, B> is defined in bun.d.ts as Without<A, B> | Without<B, A>: you may use the keys of one side or the other, never both. Two things to try, since you can compile them:

const server = Bun.serve({
port: 0,
maxRequestBodySize: 1024 * 1024,
idleTimeout: 30,
routes: {
// the params are typed from the path string
"/jobs/:id": (req) => Response.json({ id: req.params.id })
}
})
server.stop()
// @ts-expect-error: `unix` and `port` are the two sides of an XOR
Bun.serve({
unix: "/tmp/relay.sock",
port: 8080,
fetch: () => new Response("ok")
}).stop()

The first is the typical call. req.params.id is a string because BunRequest<"/jobs/:id"> computes the params from the path, which is the same type-level trick as the route-params lesson of M4. The second is rejected because a server listens on a socket or on a port, and the type says so. All of that came from reading, with no docs site.

Copy these files into the Relay project in one folder, such as src/declarations/reading/, and rename main.starter.ts to main.ts. Install fast-check with bun add -d fast-check if the project does not have it yet. Write ruleArb using only the declarations: open node_modules/fast-check/lib/fast-check.d.ts and read letrec, oneof, OneOfConstraints and WeightedArbitrary. Then run bun test in the folder.

The comment at the top of the starter lists the rules. The last one has a hint: one of the oneof constraints is documented as the way to shrink trees, and its doc comment says something about the first arbitrary you pass.

main.ts
// Relay routes jobs with a rule tree: `eq` compares a field, `not`, `and` and `or` combine rules.
// Property tests for the router need random rules, and the tree is recursive, so a plain
// fc.record can't build it. Write `ruleArb` using only fast-check's own declarations:
// open node_modules/fast-check/lib/fast-check.d.ts and read `letrec` and `oneof`.
//
// Rules:
// - ruleArb generates every kind of rule: eq, not, and, or.
// - `eq` has a field from FIELDS and a value of 1 to 8 characters. `and` and `or` hold 1 to 3 rules.
// - No rule is deeper than 3 (an `eq` has depth 0, `not` adds 1, `and`/`or` add 1 to their deepest child).
// - About half of the rules at the root are `eq`, and `not`, `and`, `or` share the rest equally
// (weights, see WeightedArbitrary).
// - When a property fails, the shrunk counter-example is small. Read the doc comment on the
// constraint that "allows to shrink trees" and note what it says about the FIRST arbitrary.
import fc from "fast-check"
export const FIELDS = ["kind", "source", "region"] as const
export type Field = (typeof FIELDS)[number]
export interface Eq {
readonly kind: "eq"
readonly field: Field
readonly value: string
}
export interface Not {
readonly kind: "not"
readonly rule: Rule
}
export interface And {
readonly kind: "and"
readonly rules: readonly Rule[]
}
export interface Or {
readonly kind: "or"
readonly rules: readonly Rule[]
}
export type Rule = Eq | Not | And | Or
export const ruleArb: fc.Arbitrary<Rule> = fc.constant({ kind: "eq", field: "kind", value: "email" })
main.test.ts
import { expect, test } from "bun:test"
import fc from "fast-check"
import { FIELDS, ruleArb, type Rule } from "./main.ts"
type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false
type Expect<T extends true> = T
export type RuleArbIsTyped = Expect<Equal<typeof ruleArb, fc.Arbitrary<Rule>>>
function depth(rule: Rule): number {
switch (rule.kind) {
case "eq":
return 0
case "not":
return 1 + depth(rule.rule)
case "and":
case "or":
return 1 + Math.max(...rule.rules.map(depth))
}
}
function size(rule: Rule): number {
switch (rule.kind) {
case "eq":
return 1
case "not":
return 1 + size(rule.rule)
case "and":
case "or":
return 1 + rule.rules.reduce((n, r) => n + size(r), 0)
}
}
function wellFormed(rule: Rule): boolean {
switch (rule.kind) {
case "eq":
return FIELDS.some((f) => f === rule.field) && rule.value.length >= 1 && rule.value.length <= 8
case "not":
return wellFormed(rule.rule)
case "and":
case "or":
return rule.rules.length >= 1 && rule.rules.length <= 3 && rule.rules.every(wellFormed)
}
}
function hasNot(rule: Rule): boolean {
switch (rule.kind) {
case "eq":
return false
case "not":
return true
case "and":
case "or":
return rule.rules.some(hasNot)
}
}
const sample = fc.sample(ruleArb, { numRuns: 2000, seed: 7 })
test("every generated rule is well formed", () => {
expect(sample.every(wellFormed)).toBe(true)
})
test("all four kinds are generated", () => {
const kinds = new Set(sample.map((r) => r.kind))
expect([...kinds].sort()).toEqual(["and", "eq", "not", "or"])
})
test("rules are nested, and never deeper than 3", () => {
const depths = sample.map(depth)
expect(Math.max(...depths)).toBe(3)
})
test("about half of the root rules are eq, and the other kinds share the rest", () => {
const share = (kind: Rule["kind"]): number => sample.filter((r) => r.kind === kind).length / sample.length
expect(share("eq")).toBeGreaterThan(0.4)
for (const kind of ["not", "and", "or"] as const) {
expect(share(kind)).toBeGreaterThan(0.1)
expect(share(kind)).toBeLessThan(0.25)
}
})
test("a failing property shrinks to a small counter-example", () => {
for (const seed of [1, 2, 3, 42]) {
const result = fc.check(
fc.property(ruleArb, (rule) => !hasNot(rule)),
{ seed }
)
expect(result.failed).toBe(true)
const [counterExample] = result.counterexample ?? []
expect(counterExample === undefined ? 99 : size(counterExample)).toBeLessThanOrEqual(3)
}
})
  • Start at exports and types in package.json, open that one file, and search for the name. Look at the end of a bundled .d.ts for its export list.
  • Overloads are tried top to bottom. A generic with a variadic tuple (fc.property) replaces a pile of overloads.
  • Constraints tell you what you may pass, and the return type tells you what changes when you do (requiredKeys).
  • JSDoc carries defaults, examples and deprecations that the types don’t show. tsc won’t warn about @deprecated.
  • Check your reading by compiling a call that must work and one that must fail.