Plugin types through declaration merging

How Express, Vue and Fastify let plugins add typed fields to shared objects. A free TypeScript lesson with examples.

More on Patterns from open source

Keep learning

Overview

chapters · patterns from open source Plugin types through declaration merging

auth.ts

Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'. In plain words: TypeScript looked up user in Express's Request type and did not find it. The common quick fix is (req as any).user. as any means "trust me, stop checking". It hides the error but causes the problems below. (req as any).user silences it every route casts again typo req.usr still compiles

2. The mechanism: interfaces with the same name merge

type aliases Duplicate identifier 'Cart'. A type alias is fixed once written. A second alias with the same name is a clash, so TypeScript flags both lines. string | undefined Both declarations add members to one Cart. coupon is optional (?), so reading it gives string | undefined. Module augmentation (reopening a module from outside) uses the same merge on a library's exported interface.

3. Three libraries, one trick

Words used in the tabs: declare module "vue": "add to the types of the vue package". declare global + namespace Express: "add to the global group of names called Express". Express types its Request on top of a global Express.Request interface that is empty on purpose. Merge into it and every handler sees req.user.

routes.ts: after the augmentation

req.user: User | undefined 'req.user' is possibly 'undefined'.

4. The trap: augment from a module, not a script

A file with no import or export is a script. A file with at least one is a module. In a script, declare module "fastify" does not add to the real package. It defines a brand-new "fastify" that hides the real one. script file (no import/export) The new module contains only db. So elsewhere fails: Module '"fastify"' has no exported member 'fastify'.

Why the script version breaks the import

the file has no import or export script file declare module "fastify" in a script a whole new module "fastify" TypeScript uses that one instead of the package your app imports fastify() error: has no exported member 'fastify' Assuming the file is a module, what does line 6 give? Property 'cache' does not exist on type 'FastifyInstance'. Step 1: the file is a module, so the block merges into the real FastifyInstance. Step 2: FastifyInstance now has Fastify's own members plus db. Step 3: nobody added cache, so TypeScript reports it as missing. A forgotten augmentation is a compile error, not an unchecked any.

5. Designing your own: the empty Register interface

Libraries leave an empty interface for you to fill. Their types read from it.

router-lib (library side)

A extends B ? X : Y is a conditional type: a type-level if/else. infer R means "whatever type sits here, call it R".

What useRouter() returns, before and after you merge

library alone: Register is empty your app merges router into Register now it matches, and infer R picks the router type TanStack Router Plugins add store properties by merging into a custom-properties interface. Merge in your resource types and t("key") checks key names.

6. The alternative: pass types through generics

A generic is a type with a blank, like Hono<…>. You fill the blank when you create the app, instead of changing a global type. Declaration merging (Express, Vue, Fastify) Global: every request everywhere gets user?. Easy to add, but types can claim a field exists where the plugin never ran. Generic context (Hono, tRPC)

Remember

declare module "lib" reopens a library's exported interfaces. Augment from a module file, or you replace the library's types. Keep runtime decoration and type augmentation in the same file. Prefer optional fields when a plugin might not run. ! Cheat code Find the library's empty interface. Merge into it with declare module from a file that has an export. Add the value at runtime next to it. → Go deeper: declaration merging and module augmentation, declaration files and @types, namespaces, type or interface?.

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
  • Databases in depth — How a query becomes work. Indexes, isolation, locks, and the plans that explain why a page is slow — not an ORM tour.
  • System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.