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

Ale*_*rff 8 typescript typescript-typings typescript2.0

使用 tsc v2.2.2

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

错误 TS4058:导出函数的返回类型具有或正在使用来自外部模块“{some path}/dist/types”的名称“{SomeInterface}”,但无法命名。

我有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) {
     // ...
  };
}
Run Code Online (Sandbox Code Playgroud)

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

错误 TS4058:导出函数的返回类型具有或正在使用来自外部模块“/folder/node_modules/some-module/dist/types”的名称“ICoolInterface”,但无法命名。

Ale*_*rff 8

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

// 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) {
     // ...
  };
}
Run Code Online (Sandbox Code Playgroud)


Rat*_*ica 3

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

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

// index.ts
import {ICoolInterface} from 'some-module'
Run Code Online (Sandbox Code Playgroud)

考虑跟踪这个GitHub 问题,他们正在考虑更改此 TypeScript 行为。

函数或变量没有显式类型注释。声明发射器推断它们的类型并尝试写入它。如果该类型来自不同的模块,则 a. 它需要添加一个导入或b。错误。

发射器可以编写额外的导入,但这会以您在代码中没有明确指出的方式改变您的 API 形状。所以我们选择了错误。

解决方法是在问题根源上添加显式类型注释。

话虽如此,我认为我们应该重新考虑这个设计决策,并无论如何添加导入。

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