typescript module_error ai_generated true

TS2669: Augmentations for the global scope can only be directly nested in external modules or ambient module declarations

ID: typescript/ts-module-augmentation-error

Also available as: JSON · Markdown
84%Fix Rate
86%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
5 active

Root Cause

Module augmentation syntax is incorrect. The file must be a module (have import/export) and use the correct declaration merging syntax.

generic

Workarounds

  1. 88% success Ensure the file is a module and use proper augmentation syntax
    // Must have at least one import/export to be a module
    import 'express';
    
    declare module 'express' {
      interface Request {
        user?: { id: string; role: string };
      }
    }
    
    export {}; // ensures this is a module

    Sources: https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation

  2. 85% success Use declare global for global scope augmentations
    export {}; // make this a module
    
    declare global {
      interface Window {
        myCustomProperty: string;
      }
    }

    Sources: https://www.typescriptlang.org/docs/handbook/declaration-merging.html#global-augmentation

Dead Ends

Common approaches that don't work:

  1. Put augmentation declarations in a non-module script file 80% fail

    Module augmentations only work inside modules (files with import/export statements)

Error Chain

Leads to:
Preceded by:
Frequently confused with: