Search code examples
typescripttypescript-typingstypescript2.0

error TS4058: Return type of exported function has or is using name X from external module Y but cannot be named


Using tsc v2.2.2

How to fix typescript compiler error:

error TS4058: Return type of exported function has or is using name '{SomeInterface}' from external module "{some path}/dist/types" but cannot be named.

I have folder with index.ts and something.ts

// index.ts
import something from './something'

// error will point on this export below
export default function () {
   return {
     resultFunctionFrom: something()
   };
}


// something.ts
import {ICoolInterface} from 'some-module'

export default function () {
  return function (rootOfEvil:ICoolInterface) {
     // ...
  };
}

I will get this error with such code:

error TS4058: Return type of exported function has or is using name 'ICoolInterface' from external module "/folder/node_modules/some-module/dist/types" but cannot be named.


Solution

  • Update: This should no longer happen in TypeScript 2.9 and resolves Issue 9944 linked below. https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#relaxing-declaration-emit-visiblity-rules

    Currently you need to explicitly import ICoolInterface in index.ts:

    // index.ts
    import {ICoolInterface} from 'some-module'
    

    Consider tracking this GitHub issue where they are considering changing this TypeScript behaviour.

    There is no explicit type annotation on the functions or variables. the declaration emitter infers their type and tries to write it. if the type is coming from a different module, then a. it needs to add an import or b. error.

    The emitter can write the additional import, but that would have been changing your API shape in a way you did not indicate clearly in your code. so we opted to error instead.

    the fix would be to add an explicit type annotation on the source of the problem.

    Having siad that, i think we should reconsider this design decision, and add imports anyways.

    Note: if you are using WebStorm, you will be warned about an unused import. You can disable the warning with the comment //noinspection ES6UnusedImports above the import. GUI alternative: press Alt + Enter on the import line with the warning. Right arrow for more options on Remove unused 'import' popup menu and choose Suppress for statement to disable the warning on this particular line.