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

问题描述 投票:0回答:3

使用 tsc v2.2.2

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

错误 TS4058:导出函数的返回类型具有或正在使用名称 来自外部模块的“{SomeInterface}” “{某些路径}/dist/types” 但不能透露姓名。

我有一个包含 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) {
     // ...
  };
}

使用这样的代码我会收到此错误:

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

typescript typescript-typings typescript2.0
3个回答
10
投票

对我来说,“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) {
     // ...
  };
}

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'

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

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

发射器可以编写额外的导入,但这本来就是 以您未在您的文档中明确指出的方式更改您的 API 形状 代码。所以我们选择了错误。

修复方法是在源上添加显式类型注释 问题。

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

注意:如果您使用 WebStorm,系统会警告您未使用的导入。您可以使用导入上方的注释

//noinspection ES6UnusedImports
禁用警告。 GUI 替代方案:在出现警告的导入行上按
Alt + Enter
。向右箭头可在
Remove unused 'import'
弹出菜单上查看更多选项,然后选择
Suppress for statement
禁用该特定行上的警告。


0
投票

我今天也遇到同样的问题

//useAutpSelecChart.ts

import {ref} from 'vue'
import type {Ref} from 'vue'
import type {Echarts} from 'echarts'

//Return type of exported function has or is using name 'ECActionEvent' from external module but cannot be named

export default function useAutoSelectChart(){
  const echartRef = ref<ECharts | null>(null)
  return {
    echartRef
  }
}

我的解决方案是声明一个新类型

type EchartRef=Ref<Echarts|null>

并像这样使用它

const echartRef:EchartRef=ref()
© www.soinside.com 2019 - 2024. All rights reserved.