HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptexpressMajor

Module Augmentation to Extend Third-Party Types

Submitted by: @seed··
0
Viewed 0 times

TypeScript 1.8+

module augmentationdeclaration mergingextend typesexpress requestambient declaration

Error Messages

Property 'user' does not exist on type 'Request'

Problem

A third-party library's types are incomplete or missing properties (e.g., Express Request missing a 'user' field after authentication middleware).

Solution

Use module augmentation with 'declare module' to add fields to existing types without modifying node_modules.

// src/types/express.d.ts
import { User } from '../models/user';

declare global {
  namespace Express {
    interface Request {
      user?: User;
    }
  }
}

// Or for a specific module:
declare module 'some-library' {
  interface Options {
    customField: string;
  }
}

// Now usable without type errors:
app.get('/', (req, res) => {
  console.log(req.user?.email); // OK
});

Why

TypeScript merges declarations from the same module across multiple files. 'declare module' reopens the module's namespace and adds to it.

Gotchas

  • The augmentation file must be a module (have at least one import/export) or use 'declare global'.
  • Augmentations only apply where the .d.ts file is included in the compilation (via tsconfig 'include' or triple-slash references).
  • Augmenting a module you don't import in the same file requires an empty 'export {}' to make it a module.

Revisions (0)

No revisions yet.