Skip to content

Declaration merging and module augmentation

Relay is getting plugins. A webhook plugin adds a "webhook.deliver" job, a reports plugin adds "report.build". The core queue should accept their payloads with full type checking, and the core should not import the plugins or list their kinds. A union in the core would have to be edited for every plugin.

TypeScript has a feature built for this: when two declarations in the same scope share a name, some of them merge into one. You have used it without noticing, since interface can be declared twice. This lesson uses it as an extension point.

Two interface declarations with the same name become one interface with all members:

interface JobPayloads {
"email.send": { to: string; subject: string }
}
interface JobPayloads {
"webhook.deliver": { url: string; body: string }
}
type Kind = keyof JobPayloads // "email.send" | "webhook.deliver"
declare const p: JobPayloads["webhook.deliver"]
const url: string = p.url

A type alias can’t do this. Declaring type JobPayloads twice is a “duplicate identifier” error. That is a real difference between the two, and the reason library authors still choose interface for types users are meant to extend.

If two declarations give the same property different types, that is an error as well. Plugins should pick distinct keys.

A registry is an interface whose keys are names and whose values are the payload types. The queue derives everything from it with keyof and indexed access (M3 lesson 3):

interface JobPayloads {
"email.send": { to: string; subject: string }
}
interface JobPayloads {
"report.build": { name: string; days: number }
}
type JobKind = keyof JobPayloads
declare function enqueue<K extends JobKind>(kind: K, payload: JobPayloads[K]): void
enqueue("report.build", { name: "weekly", days: 7 })
// @ts-expect-error: the payload of "email.send" does not fit "report.build"
enqueue("report.build", { to: "ops@example.com", subject: "hi" })
// @ts-expect-error: "sms.send" is not registered
enqueue("sms.send", { to: "1" })

K is inferred from the first argument, and JobPayloads[K] then picks the matching payload, exactly the keyed lookup of M3 lesson 3. Registering a plugin is declaring one more interface. The bug this prevents: a payload sent to a handler that expects another shape.

In the exercise all three declarations are in one file. In a real project they live in separate packages, and that needs the next feature.

A plugin in its own file can’t just redeclare interface JobPayloads, because that would create a new interface in the plugin’s module. It has to reopen the original one with declare module:

plugin.ts
export {}
declare module "bun:test" {
interface Matchers<T> {
toBeValidJobId(): void
}
}

Inside declare module "<specifier>", an interface merges with the interface of the same name in that module. Here the specifier is one that always resolves, so this compiles on its own. In Relay, core would export JobPayloads from "relay" and a plugin would write declare module "relay" { interface JobPayloads { ... } }. Two rules:

  • The file must be a module (any import or export), as the export {} line shows. Without it, the same text declares a new ambient module instead of augmenting one.
  • You can add members and merge interfaces. You can’t add a new top-level export, and you can’t change an existing declaration.

TypeScript only sees the augmentation if the file is part of the program. If a plugin’s file is never imported, its job kinds are missing from the types.

declare global does the same for the global scope: the types that exist without an import.

export {}
declare global {
interface Array<T> {
lastOrUndefined(): T | undefined
}
}
const xs = [1, 2, 3]
const last: number | undefined = xs.lastOrUndefined()

This only changes the types. You must also add the method at runtime (Array.prototype.lastOrUndefined = ...), and nothing checks that you did. Changing built-ins is a last resort. A function lastOrUndefined(xs) has no such risk. Augmenting globals is mostly for describing things a runtime or a library puts there, such as process.env keys or a window.relay object.

Function and namespace, class and interface

Section titled “Function and namespace, class and interface”

Other pairs merge too. A function and a namespace of the same name give a function with properties:

export function createQueue(name: string): string {
return `queue:${name}`
}
export namespace createQueue {
export const defaultConcurrency = 4
}
const n: number = createQueue.defaultConcurrency

The namespace must come after the function. This is how old libraries typed “a function that also has fields”. New code uses a plain object or two exports.

A class and an interface of the same name add members to the class type without writing them in the class body:

class Job {
constructor(readonly id: string) {}
}
interface Job {
describe(): string
}
Job.prototype.describe = function (this: Job) {
return `job ${this.id}`
}
declare const job: Job
const text: string = job.describe()

The two declarations merge into one type, and the compiler believes describe exists. Here you assigned it, but nothing forces that: if you forget the assignment, job.describe() compiles and crashes. It is useful for mixins and generated code, and it is a sharp tool.

Merging is action at a distance: a declaration in one file changes the type in another, and someone reading the core can’t see all of the registry. Reach for it when there is a real extension point, like plugins that you don’t control. For code you own, a union you edit or a function that takes the handlers as an argument is easier to follow. And never augment a library’s types to silence an error: the error was telling you something.

The queue’s registry has one kind. Add the two plugin kinds by declaring interface JobPayloads twice more, and see enqueue check every payload against its kind.

  • Two interface declarations with one name merge. A type alias can’t.
  • An open interface keyed by name is a registry. keyof and Registry[K] derive the rest.
  • declare module "x" in a file that is a module reopens x’s interfaces.
  • declare global extends the global scope. It changes types only, never the runtime.
  • Function + namespace and class + interface merge too. Use them rarely.
  • Merging works at a distance. Use it for real extension points only.