typescript type_error ai_generated true

error TS2742: The inferred type of 'X' cannot be named without a reference to 'Y'

ID: typescript/ts2742-inferred-type-not-portable

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
5 active

Root Cause

TypeScript can infer the type but can't express it in declaration files. Common with monorepos.

generic

Workarounds

  1. 92% success Add the dependency that defines the type to your package.json dependencies (not just devDependencies)
    not just devDependencies

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

  2. 88% success Add an explicit return type annotation to avoid relying on inference
    export function create(): ExplicitReturnType { ... }

    Sources: https://www.typescriptlang.org/docs/handbook/2/functions.html#return-type-annotations

  3. 82% success In monorepos, ensure TypeScript project references are set up correctly
    // tsconfig.json for monorepo packages:
    {
      "compilerOptions": {
        "composite": true,
        "declaration": true,
        "declarationMap": true
      },
      "references": [
        { "path": "../shared" }
      ]
    }
    
    // Run: tsc --build to compile in dependency order

    Sources: https://www.typescriptlang.org/docs/handbook/project-references.html

Dead Ends

Common approaches that don't work:

  1. Set declaration: false in tsconfig 65% fail

    Breaks libraries that need .d.ts files for consumers

  2. Use any as the explicit type 75% fail

    Loses all type information for consumers

Error Chain

Leads to:
Preceded by: