错误 TS4058:Return 类型的导出函数具有或正在使用来自外部模块 Y 的名称 X 但无法命名

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

如何修复打字稿编译器错误:

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

我有 index.tssomething.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) {
     // ...
  };
}

我会用这样的代码得到这个错误:

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.

对我来说 return 在 'index.ts' 中输入 :any 作为默认导出就成功了。无需导出 ICoolInterface。也许像这样使用 :any 是一种不好的做法,但至少它可以编译并且我在 'something.ts' 中的函数用 arg 类型和 return 类型描述得很好。 所以这会起作用:

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

// error will point on this export below
// ------------------------\/-----------
export default function ():any { // trouble solver
// ------------------------/\-----------
   return {
     resultFunctionFrom: something()
   };
}


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

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

更新: 这不应再发生在 TypeScript 2.9 中,并解决了下面链接的问题 9944。 https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#relaxing-declaration-emit-visiblity-rules

目前您需要在 index.ts 中显式导入 ICoolInterface:

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

考虑跟踪此 GitHub issue 他们正在考虑更改此 TypeScript 行为的地方。

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.

注意:如果您使用的是 WebStorm,系统会警告您有未使用的导入。您可以使用导入上方的注释 //noinspection ES6UnusedImports 禁用警告。 GUI 替代方案:在带有警告的导入行上按 Alt + EnterRemove unused 'import' 弹出菜单上的更多选项的右箭头并选择 Suppress for statement 以禁用此特定行的警告。