Skip to content
JL

Home

About

Blog

Contact

Shop

Portfolio

Privacy

TOS

Click to navigate

  1. Home
  2. Joshua R. Lehman's Blog
  3. TypeScript Declaration Merging: Extend Contracts

Table of contents

  • Share on X
  • Discuss on X

Related Articles

Writing Your Own Declaration Files in TypeScript
TypeScript
12m
Oct 27, 2026

Writing Your Own Declaration Files in TypeScript

A declaration file is an API design artifact. Learn to model JavaScript honestly, distinguish modules from globals, and test the contract consumers will actually import.

#TypeScript#Declaration Files+4
TypeScript Declaration Files: JavaScript Contracts
TypeScript
11m
Oct 13, 2026

TypeScript Declaration Files: JavaScript Contracts

A .d.ts file is not an implementation. It is a public contract that lets TypeScript reason about JavaScript safely and usefully.

#TypeScript#Declaration Files+4
TypeScript React Hooks: State, Effects, and Refs
TypeScript
12m
Nov 17, 2026

TypeScript React Hooks: State, Effects, and Refs

Hooks are small APIs with large consequences. Learn patterns for inferrable state, explicit nullable values, effect cleanup, refs, reducers, and custom hooks that remain understandable as a feature grows.

#TypeScript#React+5
Ask me anything! 💬

© Joshua R. Lehman

Full Stack Developer

Crafted with passion • Built with modern web technologies

2026 • All rights reserved

Contents

  • What Actually Merges
  • Interface Merging for Stable Extension Points
  • Namespaces Model Specific Runtime Shapes
  • Module Augmentation Must Follow Runtime Extension
  • Recognize the Sharp Edges
  • Key Takeaways
TypeScript

TypeScript Declaration Merging: Extend Contracts

November 3, 2026•6 min read
Joshua R. Lehman
Joshua R. Lehman
Author
Centred type-contract merge diagram showing two declarations joining into one verified API surface
TypeScript Declaration Merging: Extend Contracts

TypeScript declaration merging lets separate declarations with the same name become one type-level contract. Used well, it models JavaScript patterns that are genuinely extensible: a framework request object gains verified middleware state, a callable function exposes properties, or a plugin adds a method to a class it actually patches at runtime.

Used casually, it creates a more subtle any: the compiler believes a property exists while JavaScript does not. The rule that keeps merging honest is simple: merge a declaration only when there is a corresponding runtime relationship—or when you are deliberately defining a pure type extension point that consumers must implement themselves.

What Actually Merges

TypeScript declarations create different kinds of entities: types, values, and namespaces. The official declaration-merging guide (opens in new tab) explains that which entities a declaration creates determines which combinations can merge.

DeclarationNamespaceTypeValue
interfaceNoYesNo
classNoYesYes
functionNoNoYes
namespaceYesNoYes
enumNoYesYes

This table answers a surprising number of questions. Two interfaces can merge because both contribute type members. A function and namespace can merge because the namespace adds a value-side property space. A type alias does not merge like an interface; choosing type when you intend third-party extension closes that particular door.

Do not reach for merging just because two concepts have similar names. A merge is a declaration-level promise that they represent the same public thing.

Interface Merging for Stable Extension Points

Interface merging joins members by name. It is a natural fit when a library intentionally exposes an object shape for consumers to extend:

interface AppEvents {
  "order.created": { orderId: string };
}
 
interface AppEvents {
  "order.cancelled": { orderId: string; reason: string };
}
 
type EventName = keyof AppEvents;

The result has both event members. This can be a clean plugin architecture: the core owns a stable AppEvents extension point, feature packages add their own events, and a typed emitter derives valid names and payloads from the combined interface.

function emit<Name extends keyof AppEvents>(
  name: Name,
  payload: AppEvents[Name]
) {
  // runtime dispatch
}
 
emit("order.created", { orderId: "ord_42" });

The extension point must be intentional and governed. If two packages add the same non-function property with incompatible types, TypeScript reports a conflict. That is useful evidence that the packages disagree about who owns the contract. Do not “fix” it by widening the property to unknown; resolve the ownership or namespace the event.

Overloads have special merge ordering rules. Later interface declarations take precedence in overload lists, while specialized literal signatures can be prioritized. Avoid relying on this as a clever dispatch mechanism. If overload order is semantically important, write and type-test the public API in one place so a future augmentation cannot quietly change inference.

Namespaces Model Specific Runtime Shapes

Namespaces are most useful in declarations when JavaScript really has a value with attached static members or nested types. A callable formatter with a configuration property is a classic example:

declare function formatMoney(cents: number): string;
 
declare namespace formatMoney {
  let currency: "CAD" | "USD";
  function configure(next: { currency: "CAD" | "USD" }): void;
}
 
export = formatMoney;

This models runtime JavaScript like formatMoney.currency = "CAD". The namespace is not creating a magical object; it describes properties that must exist on the function value. The earlier declaration-files article covered this pattern because it is common in CommonJS-era APIs and still appears in interoperability layers.

Namespaces can also merge with classes and enums to describe static helpers. Use that capability to reflect a real API, not to hide unrelated utilities under a familiar class name. Modern ESM exports are often clearer as separate named exports.

Type Merging Does Not Create JavaScript

Extending an interface or augmenting a module only changes what the compiler accepts. If a consumer calls a method added by a declaration, your runtime code or imported plugin must create that method before the call. Type correctness without runtime setup is a production failure waiting to happen.

Module Augmentation Must Follow Runtime Extension

Module augmentation lets an application or plugin add declarations to an existing module. It is ideal for middleware that truly extends a framework object:

// types/request-context.d.ts
import "express-serve-static-core";
 
declare module "express-serve-static-core" {
  interface Request {
    requestContext: { requestId: string; actorId?: string };
  }
}

The runtime must establish the property on every path that uses it:

app.use((request, _response, next) => {
  request.requestContext = { requestId: crypto.randomUUID() };
  next();
});

Now types and behaviour agree. The augmentation documents a capability installed by middleware. Without that middleware, request.requestContext is not merely missing from type inference—it is missing at runtime.

The module specifier in declare module "..." is resolved using normal import rules. Match the package and export your code actually imports. The TypeScript documentation notes two important limits: augmentations patch existing declarations rather than adding arbitrary new top-level exports, and default exports cannot be augmented by name. If you need to change a default export API, create a wrapper module with an explicit public contract instead.

For a plugin that patches a class prototype, keep activation explicit:

// observable-map.ts
import { Observable } from "./observable";
 
declare module "./observable" {
  interface Observable<T> {
    map<U>(transform: (value: T) => U): Observable<U>;
  }
}
 
Observable.prototype.map = function (transform) {
  return new Observable(transform(this.value));
};

Consumers must import the plugin side effect before calling map. If that import is easy to forget, provide one canonical entry point that imports the plugin and re-exports the configured API, rather than requiring every consumer to remember invisible initialization order.

Recognize the Sharp Edges

Merging is powerful because it is ambient: a declaration can affect distant files. That makes scope and discoverability important.

  • Prefer local module augmentation files with clear names over a giant global types.d.ts.
  • Add a runtime test that the property or method exists after the required initialization.
  • Add a type test that imports through the public entry point and verifies the intended member.
  • Keep optional properties optional when middleware or plugin activation is not guaranteed.
  • Do not use augmentation to correct a bad third-party API silently; use a wrapper or contribute a fix when the correction should be broadly true.

Global augmentation has the largest blast radius. It can be appropriate when a side-effect module truly extends a built-in, but it should be rare. The global-modifying module template (opens in new tab) is worth reading before adding a prototype method: global conflicts and incomplete activation are harder to debug than a plain explicit helper function.

Use extension points as part of an API design. Name them after the domain, document ownership, decide collision policy, and test a small plugin implementation. If you cannot describe who may extend a declaration and why, a plain composition function is usually safer.

Key Takeaways

  • Declaration merging joins compatible declarations for the same public concept; it does not create runtime values or methods.
  • Interfaces are good intentional type extension points; type aliases are not open in the same way.
  • Namespaces can model callable or class-like JavaScript values with attached members when that shape exists at runtime.
  • Module augmentation is appropriate only when a plugin or application actually extends the imported module’s behaviour.
  • Keep ambient effects scoped, test both runtime activation and consumer-facing types, and prefer explicit composition when extension ownership is unclear.

Next, we return to Next.js and make cache freshness dependable with revalidation and invalidation: time, tags, mutation paths, and observing whether users actually receive the state the system intends.