Skip to content
jsmanifest logojsmanifest

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

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

Learn how to add type definitions to untyped npm packages using TypeScript's declare module augmentation, avoiding the critical import/export pitfall that breaks type merging.

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.

flowchart LR
    Import("import from untyped package") --> Error("compiler error: any type")
    Error --> Unsafe("suppress errors, lose type safety")
    style Error stroke:#fbbf24,fill:#3a2f0b,color:#fef3c7
    style Unsafe stroke:#ef4444,fill:#450a0a,color:#fca5a5

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.

flowchart LR
    Import("import from untyped package") --> Declare("declare module in project")
    Declare --> Safe("typed imports, full IDE support")
    style Declare stroke:#c084fc,fill:#3b0764,color:#f3e8ff,stroke-width:4px
    style Safe stroke:#34d399,fill:#0b3b2e,color:#d1fae5

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.

flowchart TD
    DeclareModule("declare module statement")
    DeclareModule --> Script("file has no import/export")
    DeclareModule --> Module("file has import or export")
    Script --> Ambient("ambient module: creates new module")
    Module --> Augment("module augmentation: merges with existing")
    style Ambient stroke:#7c9cf0,fill:#142544,color:#eaf2ff
    style Augment stroke:#7c9cf0,fill:#142544,color:#eaf2ff

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

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.

flowchart LR
    File("declaration file") --> Check("contains import or export?")
    Check -->|no| Script("global script mode")
    Check -->|yes| Module("module mode")
    Script --> New("declare module creates new ambient module")
    Module --> Merge("declare module merges with package types")
    style Script stroke:#fbbf24,fill:#3a2f0b,color:#fef3c7
    style New stroke:#ef4444,fill:#450a0a,color:#fca5a5
    style Merge stroke:#34d399,fill:#0b3b2e,color:#d1fae5
    style Module stroke:#c084fc,fill:#3b0764,color:#f3e8ff,stroke-width:4px

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

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.

flowchart LR
    TSConfig("tsconfig.json typeRoots") --> TypesDir("types/ directory")
    TypesDir --> Package1("csv-helpers/index.d.ts")
    TypesDir --> Package2("legacy-logger/index.d.ts")
    TypesDir --> Package3("express/index.d.ts")
    Package1 --> Resolve("TypeScript resolves module types")
    Package2 --> Resolve
    Package3 --> Resolve
    style TSConfig stroke:#c084fc,fill:#3b0764,color:#f3e8ff,stroke-width:4px
    style Resolve stroke:#34d399,fill:#0b3b2e,color:#d1fae5

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.

flowchart LR
    Augment("augmentation declaration") --> Interface("interface")
    Augment --> TypeAlias("type alias")
    Augment --> Class("class")
    Interface --> Merge("merges with original")
    TypeAlias --> Overwrite("overwrites original")
    Class --> Overwrite
    style Merge stroke:#34d399,fill:#0b3b2e,color:#d1fae5
    style Overwrite stroke:#fbbf24,fill:#3a2f0b,color:#fef3c7
    style Interface stroke:#7c9cf0,fill:#142544,color:#eaf2ff

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 TypeAugmentation BehaviorWorkaround if Not Mergeable
InterfaceMerges with originalNone needed
Type AliasOverwrites completelyUse intersection type with import
ClassOverwrites completelyExtend class or use interface augmentation for methods
NamespaceMerges with originalNone 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:

export {};
 
declare module 'request-package' {
  export function request(config: RequestConfig): Promise<Response>;
}

The augmentation replaces all existing overloads with the single new signature. TypeScript does not merge function overload lists across augmentation boundaries. Adding overloads requires redeclaring all signatures:

export {};
 
declare module 'request-package' {
  export function request(url: string): Promise<Response>;
  export function request(url: string, options: RequestOptions): Promise<Response>;
  export function request(config: RequestConfig): Promise<Response>;
}

This duplication introduces maintenance risk. When the package updates its signatures, the augmentation must update as well. For packages that change frequently, this becomes unsustainable.

Namespace augmentation follows interface merging rules. A package defines a namespace:

// Original package
export namespace Utils {
  export function helper(): void;
}

Augmentation extends it:

export {};
 
declare module 'utils-package' {
  export namespace Utils {
    export function newHelper(): void;
  }
}

The augmented namespace merges with the original. Both helper and newHelper remain available. Namespaces support the same merging behavior as interfaces.

Augmentation order matters when multiple declaration files modify the same module. TypeScript processes files in the order they appear in the compilation. Later augmentations build on earlier ones. Circular augmentation dependencies create resolution errors:

// file-a.d.ts
import type { TypeFromB } from './file-b';
declare module 'package' {
  export type A = TypeFromB;
}
 
// file-b.d.ts
import type { TypeFromA } from './file-a';
declare module 'package' {
  export type B = TypeFromA;
}

This circular reference causes a compilation error. Breaking the cycle requires restructuring the augmentations or consolidating them into a single file.

Frequently Asked Questions

Can I augment built-in TypeScript types like Array or Promise?

TypeScript allows augmentation of built-in types through the global scope. Use declare global with an export {} statement to ensure module mode, then augment the interface. For example, adding a method to Array requires declare global { interface Array<T> { myMethod(): T; } }. This pattern applies to any global type, but changes affect the entire project and may conflict with libraries that make similar augmentations.

What happens if I declare a module that matches a real package but forget the import/export statement?

The declaration file becomes a global script, and the declare module creates a new ambient module that shadows the real package. TypeScript uses the ambient declaration instead of the package's actual types, and existing typed members from the package disappear. Adding export {} at the top of the file converts it to a module and enables proper augmentation that merges with the package types.

How do I augment a package that has no types at all versus one that ships partial types?

The approach remains identical for both cases. Create a declaration file with export {} at the top, then use declare module 'package-name' to define or extend types. For packages with no types, the augmentation creates the entire type definition. For packages with partial types, the augmentation merges with existing definitions if using interfaces or overwrites them if using type aliases or classes.

Can I split augmentations for a single package across multiple files?

TypeScript merges all augmentations for a module across the entire compilation. Multiple files can contain declare module 'same-package' blocks, and TypeScript combines them. Each file must include export {} to function as a module. The augmentations accumulate in the order TypeScript processes the files, determined by the include patterns in tsconfig.json.

Why does my augmentation work in VSCode but fail during tsc compilation?

VSCode and the TypeScript compiler may use different tsconfig.json files or different file inclusion patterns. Check that the declaration file appears in the include array or that its directory is listed in typeRoots. Running tsc --listFiles shows which files TypeScript includes in the compilation. If the declaration file is missing from that list, adjust the include or typeRoots configuration.

Production Patterns: Maintaining Type Safety Without DefinitelyTyped

Module augmentation enables full type safety for untyped dependencies without external coordination. The declaration files live in source control, version alongside application code, and remain under direct team control. When the underlying package changes, updating the local declarations requires a single commit rather than a pull request to an external repository.

This approach scales to dozens of untyped packages in large codebases. A dedicated types/ directory organizes augmentations by package name, mirroring the structure of @types and making maintenance straightforward. Teams can establish conventions for augmentation reviews, testing type coverage, and updating declarations when dependencies change.

The import/export rule determines success or failure. Every declaration file must contain at least one import or export statement to function as module augmentation. A file without either becomes a global script where declare module creates ambient modules that shadow rather than merge with package types. The single line export {} suffices to enable augmentation behavior.

Interface augmentation merges with original definitions, preserving existing members while adding new ones. Type aliases, classes, and function signatures overwrite completely, requiring intersection types or redeclaration of all signatures when extending them. Understanding these merging rules prevents data loss and maintains type accuracy across package updates.

The patterns demonstrated here apply to both untyped packages and partially typed packages that need extension. TypeScript treats both cases identically once the declaration file structure is correct. Local augmentation provides complete flexibility to define types that match actual runtime behavior, regardless of whether upstream maintainers have published types or plan to do so.

Sources