typescript module_error ai_generated true

TS2307: Cannot find module 'X' or its corresponding type declarations

ID: typescript/ts2307-cannot-find-module

Also available as: JSON · Markdown
85%Fix Rate
88%Confidence
340Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
5 active

Root Cause

TypeScript cannot resolve the import. Either the module or its @types/ package is missing.

generic

Workarounds

  1. 90% success Install the @types/ package for the module
    npm install --save-dev @types/module-name

    Sources: https://www.typescriptlang.org/docs/handbook/2/type-declarations.html

  2. 85% success Check tsconfig.json paths and moduleResolution settings
    Check tsconfig.json paths and moduleResolution settings

    Sources: https://www.typescriptlang.org/tsconfig#moduleResolution

  3. 82% success Create a declaration file with: declare module 'package-name'
    // Create src/types/untyped-modules.d.ts:
    declare module 'some-untyped-package' {
      export function doSomething(input: string): void;
      export default function main(): void;
    }
    // Or for wildcard (e.g., CSS modules):
    declare module '*.css' {
      const classes: { [key: string]: string };
      export default classes;
    }

    Sources: https://www.typescriptlang.org/docs/handbook/modules/reference.html#ambient-modules

Dead Ends

Common approaches that don't work:

  1. Add // @ts-ignore above the import 72% fail

    Silences the error but you lose all type safety for that module

  2. Create an empty .d.ts file 65% fail

    Gives wrong types (everything becomes any), causing runtime bugs

Error Chain

Leads to:
Preceded by:
Frequently confused with: