TypeScript declare module Augmentation in 2026: Adding Types to Untyped npm Packages Without DefinitelyTyped

This article was written with the assistance of AI, under human supervision and review.

TypeScript projects frequently depend on npm packages that ship no type definitions. The package works at runtime, but every import triggers compiler errors. The @types namespace exists for popular libraries, yet thousands of smaller packages remain untyped. When npm install @types/your-package returns a 404, developers face a choice: abandon type safety for that dependency or write declarations manually.

The standard advice points to DefinitelyTyped, a central repository where contributors submit type definitions for review and publication. This process takes weeks and requires ongoing maintenance as the underlying package evolves. For internal tools, proprietary packages, or rapidly changing APIs, DefinitelyTyped becomes a bottleneck rather than a solution.

TypeScript provides declare module for local augmentation, which adds types directly in the consuming project. The declaration file lives alongside application code, versioned in the same repository, and remains under direct control. Changes to the package API require only a local edit, no pull request to an external repository.

This post demonstrates the mechanics of declare module, the critical distinction between global scripts and module augmentation, and the setup required to make TypeScript recognize local type declarations. The patterns here apply to TypeScript 5.x and 6.0, with references to the official tsconfig documentation for configuration fields.

Key Takeaways

  • declare module creates type definitions for untyped npm packages without submitting to DefinitelyTyped.
  • A declaration file MUST contain at least one import or export statement to function as module augmentation; files without either become global scripts where declare module creates new ambient modules that do not merge with existing types.
  • Place declaration files in a types/ directory and configure typeRoots in tsconfig.json to include that path (the typeRoots field accepts an array of directory paths relative to the tsconfig file).
  • Interface declarations inside declare module merge with existing package types, while type aliases and classes overwrite them completely.
  • The types field in package.json points to the main declaration file when bundling types with a published package (as documented in Publishing Declaration Files).

Understanding Module Augmentation vs Ambient Declarations

TypeScript distinguishes between two uses of declare module: ambient module declarations and module augmentation. Ambient declarations create new modules from scratch, typically for global scripts or libraries that define global variables. Module augmentation extends existing modules by merging new declarations with the original type definitions.

The difference determines whether TypeScript merges the new declarations or treats them as separate definitions. When a file contains no import or export statements, TypeScript treats it as a global script. A declare module in a global script creates a new ambient module. If the module name matches an installed package, the ambient declaration shadows the package's original types rather than augmenting them.

When a file includes at least one import or export statement, TypeScript treats it as a module. A declare module in a module file becomes augmentation. The compiler merges the new declarations with the package's existing types, preserving original definitions while adding new members.

This distinction surfaces in a common failure mode: developers write a declaration file with declare module "some-package", place it in the project, but omit any import or export. The file becomes a global script. The declared module takes precedence over the actual package types, and existing typed members disappear. Adding a single export {} at the top of the file converts it to a module, enabling augmentation behavior.

The official tsconfig documentation does not explicitly label this import/export requirement in a single section, but the behavior follows from TypeScript's module system semantics. A file without imports or exports exists in the global scope, where declare module introduces a new identifier. A file with imports or exports becomes a module, where declare module extends an existing identifier.

Creating Declaration Files for Untyped Packages

An untyped package exports functions, classes, or objects with no accompanying .d.ts files. TypeScript infers the module as any, providing no autocomplete or error checking. A declaration file supplies the missing type information.

Consider an untyped utility package csv-helpers that exports a single function:

// node_modules/csv-helpers/index.js module.exports.parseCSV = function(input) { return input.split('\n').map(line => line.split(',')); }; 

TypeScript sees this import as any:

import { parseCSV } from 'csv-helpers'; // parseCSV has type any const result = parseCSV(data); 

Create a declaration file in types/csv-helpers/index.d.ts:

export {}; declare module 'csv-helpers' { export function parseCSV(input: string): string[][]; } 

The export {} statement converts this file into a module, enabling augmentation. The declare module block specifies the module name exactly as it appears in imports. The export function declaration provides the function signature.

TypeScript module augmentation workflow

TypeScript module augmentation workflow

After adding the declaration file, configure TypeScript to recognize it. The typeRoots option in tsconfig.json tells TypeScript where to look for type declarations. By default, TypeScript searches node_modules/@types directories. Adding a custom path includes local declarations:

{ "compilerOptions": { "typeRoots": [ "./node_modules/@types", "./types" ] } } 

This configuration searches both the standard @types packages and the local types/ directory. The typeRoots field accepts relative paths from the tsconfig.json location. When typeRoots is set, TypeScript includes only packages under those directories, excluding all other @types locations unless explicitly listed.

TypeScript now recognizes parseCSV with its declared signature. Autocomplete suggests the function, the compiler validates argument types, and return values receive proper inference.

For packages with multiple exports, declare each member:

export {}; declare module 'csv-helpers' { export function parseCSV(input: string): string[][]; export function serializeCSV(data: string[][]): string; export const CSV_DELIMITER: string; } 

Class-based packages require class declarations:

export {}; declare module 'legacy-logger' { export class Logger { constructor(name: string); log(message: string): void; error(error: Error): void; } } 

Generic functions and interfaces work the same way:

export {}; declare module 'cache-lib' { export interface Cache<T> { get(key: string): T | undefined; set(key: string, value: T): void; } export function createCache<T>(): Cache<T>; } 

The structure matches standard TypeScript module syntax. The declare module wrapper scopes all declarations to the specified module name. The export keyword on each member makes it available to consumers.

The Critical Import Rule: Global Script vs Module Augmentation

The import/export requirement determines whether augmentation succeeds or fails. A declaration file without import or export becomes a global script, where declare module creates a new ambient module instead of merging with existing types.

This appears most commonly when augmenting packages that already ship partial types. Express.js provides base types in @types/express, but applications need to add custom properties to request objects. A declaration file extends the Request interface:

declare module 'express-serve-static-core' { interface Request { user?: { id: string; email: string }; } } 

Without an import or export, this file becomes a global script. TypeScript treats the declare module as a new ambient module declaration. The original Express types remain unchanged, and req.user stays untyped.

Adding a single export statement fixes the issue:

export {}; declare module 'express-serve-static-core' { interface Request { user?: { id: string; email: string }; } } 

The export {} exports nothing but converts the file into a module. Now declare module functions as augmentation, and the Request interface merges with the existing definition from @types/express. The user property becomes available on all request objects with full type support.

The same pattern applies to any package with existing types. Augmenting a typed package requires the import/export conversion. Augmenting an untyped package from scratch also requires it, because the absence of types does not change TypeScript's module resolution behavior.

A common variation uses an actual import instead of export {}:

import type { Request } from 'express-serve-static-core'; declare module 'express-serve-static-core' { interface Request { user?: { id: string; email: string }; } } 

The import type statement serves dual purposes: it converts the file into a module and provides type references for use in the augmentation. This approach makes sense when the augmentation references types from the package being extended.

Projects often collect multiple augmentations in a single file:

export {}; declare module 'express-serve-static-core' { interface Request { user?: { id: string; email: string }; } } declare module 'csv-helpers' { export function parseCSV(input: string): string[][]; } 

One export {} at the top suffices for the entire file. Each declare module block augments a different package. The file remains a module throughout, enabling augmentation for all declarations.

Augmenting Existing Types in Third-Party Libraries

Packages with partial type coverage need augmentation to fill gaps. A library might type core functionality but omit newer features, or expose untyped plugin hooks. Augmentation adds the missing pieces without forking the package or waiting for upstream changes.

Consider a charting library with typed chart creation but untyped configuration options:

// Existing types from @types/chart-lib export function createChart(config: any): Chart; export interface Chart { render(): void; } 

The config parameter accepts any, losing all type safety. Augmentation defines the configuration shape:

export {}; declare module 'chart-lib' { interface ChartConfig { width: number; height: number; data: Array<{ x: number; y: number }>; options?: { title?: string; colors?: string[]; }; } export function createChart(config: ChartConfig): Chart; } 

The augmented createChart declaration overwrites the original. For functions, TypeScript uses the most recently declared signature. The new signature replaces the any parameter with a structured interface.

Interface augmentation uses merging instead of replacement. When augmenting an interface, TypeScript combines both definitions:

export {}; declare module 'chart-lib' { interface Chart { // Original members remain available exportImage(): Blob; setTheme(theme: 'light' | 'dark'): void; } } 

The augmented Chart interface includes render() from the original definition plus the two new methods. Both old and new members coexist. This merging behavior applies only to interfaces and namespaces, not to type aliases or classes.

Real-world augmentation often extends plugin systems. Testing libraries provide hooks for custom matchers:

export {}; declare module 'vitest' { interface Assertion<T = any> { toBeWithinRange(floor: number, ceiling: number): T; } } 

After this augmentation, custom matchers appear in autocomplete and pass type checking:

import { expect } from 'vitest'; expect(value).toBeWithinRange(10, 20); 

TypeScript declaration merging in action

TypeScript declaration merging in action

Some packages expose global namespaces that need extension. A utility library might define a global namespace for configuration:

export {}; declare global { namespace UtilConfig { interface Settings { apiEndpoint: string; timeout: number; } } } 

The declare global block augments the global scope rather than a specific module. This pattern works for libraries that add properties to Window, global, or other global objects.

Augmenting deep module paths follows the same rules:

export {}; declare module 'framework/internal/helpers' { export function internalHelper(param: string): void; } 

The module path must match exactly as it appears in imports. TypeScript resolves nested paths like framework/internal/helpers the same way it resolves top-level module names.

Project Structure and tsconfig Setup for Declaration Files

TypeScript discovers declaration files through the typeRoots and types options. A standard project structure places all custom declarations in a dedicated directory:

project/ ├── src/ │ ├── index.ts │ └── app.ts ├── types/ │ ├── csv-helpers/ │ │ └── index.d.ts │ ├── legacy-logger/ │ │ └── index.d.ts │ └── express/ │ └── index.d.ts ├── package.json └── tsconfig.json 

Each subdirectory under types/ corresponds to a package name. The index.d.ts file contains the augmentation for that package. This mirrors the structure of node_modules/@types and helps TypeScript resolve the correct declarations.

The tsconfig.json includes this directory in typeRoots:

{ "compilerOptions": { "target": "ES2022", "module": "ESNext", "moduleResolution": "bundler", "strict": true, "typeRoots": [ "./node_modules/@types", "./types" ] }, "include": ["src/**/*", "types/**/*"] } 

The typeRoots field lists all directories to search for type packages. Order matters: TypeScript searches from first to last, and the first matching package wins. Including ./types after ./node_modules/@types allows local declarations to override installed packages when needed.

The include array must list both source files and type declaration files. TypeScript compiles everything matching these patterns. Omitting types/**/* from include causes the compiler to ignore the declarations.

For projects that augment only a few packages, a single declaration file works:

project/ ├── src/ ├── types.d.ts ├── package.json └── tsconfig.json 

The types.d.ts file at the project root contains all augmentations:

export {}; declare module 'csv-helpers' { export function parseCSV(input: string): string[][]; } declare module 'legacy-logger' { export class Logger { constructor(name: string); log(message: string): void; } } 

This approach eliminates the need for typeRoots configuration. TypeScript automatically includes .d.ts files from the include pattern. For small projects or quick prototypes, this structure reduces overhead.

Monorepos require careful path configuration. Packages sharing type augmentations place them in a shared location:

monorepo/ ├── packages/ │ ├── app-a/ │ ├── app-b/ │ └── shared-types/ │ └── index.d.ts └── package.json 

Each package's tsconfig.json references the shared types:

{ "compilerOptions": { "typeRoots": [ "../../node_modules/@types", "../../packages/shared-types" ] } } 

Relative paths resolve from the tsconfig.json location. This setup allows multiple packages to share augmentations without duplication.

The types field restricts which @types packages TypeScript includes. By default, all visible @types packages load automatically. Setting types to a specific list limits inclusion:

{ "compilerOptions": { "types": ["node", "jest"], "typeRoots": ["./node_modules/@types", "./types"] } } 

This configuration includes only @types/node and @types/jest from node_modules/@types, plus all packages from the local types/ directory. The types array applies only to @types packages, not to custom typeRoots entries. Local declarations always load when their directory appears in typeRoots.

Projects publishing packages with bundled types set the types field in package.json:

{ "name": "my-package", "version": "1.0.0", "main": "./dist/index.js", "types": "./dist/index.d.ts" } 

The types field in package.json points to the main declaration file. TypeScript resolves imports from this package using the specified .d.ts file. The typings field serves as a synonym for types and works identically.

Common Pitfalls: When Augmentation Overwrites Instead of Merges

TypeScript merges interface declarations but overwrites type aliases, classes, and function signatures. This difference causes frequent confusion when augmenting packages with mixed declaration types.

Consider a package that exports a type alias for configuration:

// Original package types export type Config = { apiKey: string; timeout: number; }; 

Augmentation attempts to add a field:

export {}; declare module 'config-package' { export type Config = { debug: boolean; }; } 

This augmentation completely replaces the original type. The augmented Config contains only debug, losing apiKey and timeout. Type aliases do not merge. The augmentation overwrites the entire definition.

The same failure mode affects classes:

// Original package export class Logger { log(message: string): void; } // Augmentation export {}; declare module 'logger-package' { export class Logger { setLevel(level: string): void; } } 

The augmented Logger class replaces the original. The log method disappears, and only setLevel remains. Class declarations do not support merging.

Converting type aliases to interfaces enables merging:

// Original package (if you control it) export interface Config { apiKey: string; timeout: number; } // Augmentation export {}; declare module 'config-package' { export interface Config { debug: boolean; } } 

Now Config includes all three properties. Interface augmentation merges declarations, preserving original members while adding new ones.

When the original package uses type aliases and cannot be modified, augmentation requires a workaround. Intersection types combine the original type with new properties:

export {}; import type { Config as OriginalConfig } from 'config-package'; declare module 'config-package' { export type Config = OriginalConfig & { debug: boolean; }; } 

The augmentation imports the original type and creates a new type that intersects it with the additional properties. This preserves the original shape while extending it. The technique works but introduces coupling to the package's internal structure.

Declaration Type Augmentation Behavior Workaround if Not Mergeable
Interface Merges with original None needed
Type Alias Overwrites completely Use intersection type with import
Class Overwrites completely Extend class or use interface augmentation for methods
Namespace Merges with original None needed

Function overloads experience similar issues. A package exports a function with multiple signatures:

// Original package export function request(url: string): Promise<Response>; export function request(url: string, options: RequestOptions): Promise<Response>; 

Augmentation adds a third signature:

Source:https://dev.to/jsmanifest/typescript-declare-module-augmentation-in-2026-adding-types-to-untyped-npm-packages-without-5b7j

Related posts