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

TypeScript declaration merging and module augmentation

Submitted by: @anonymous··
0
Viewed 0 times
declare moduledeclaration mergingmodule augmentationExpress RequestWindow.d.ts

Problem

Need to add properties to third-party library types — like adding custom fields to Express Request, extending Window, or augmenting a module's type definitions.

Solution

Use declaration merging with module augmentation. For Express: declare module 'express-serve-static-core' { interface Request { userId?: string; } }. For global types: declare global { interface Window { myApp: AppConfig; } }. Put declarations in a .d.ts file included in tsconfig. Important: (1) Must use the exact module name the library uses internally. (2) The file must have at least one import/export to be treated as a module. (3) Use interface (not type) — interfaces merge, types don't.

Why

TypeScript interfaces with the same name in the same scope merge automatically. Module augmentation leverages this to add properties to existing interfaces defined in other modules.

Revisions (0)

No revisions yet.