首页 > 解决方案 > 导出的变量 X 具有或正在使用来自外部模块 Z 的名称 Y,但无法命名

问题描述

{ compilerOptions: {declaration: true }}在这种情况下,在我的 tsconfig.json 中使用 TS 3.9 时出现以下错误:

// a.ts
export const key = 1234
export const obj = {
    [key]: 1
};
export default obj;

// b.ts
import A from "./a";
import { key} from "./a"

// Exported variable 'theExport' has or is using name 'key' from external module "c:/tsexample/src/a" but cannot be named.ts(4023)
const theExport  = {
  A: A,
  B: 2,
  C: 3,
};
export default theExport
// Exported variable 'theExport' has or is using name 'key' from external module "c:/tsexample/src/a" but cannot be named.ts(4023)

对相关问题的评论中,当时 TS 的 PM 提出了两种解决方法:

  1. 显式导入类型
  2. 显式声明导出的类型(发生错误的地方)

(1) 在这种情况下不起作用。我尝试从“a”导出所有内容并在“b”中导入所有内容,但错误消息没有任何区别。

唯一有效的是这个非常冗长且难以维护的显式类型注释:

// updated b.ts
import A from "./a";

const theExport: {
    // https://github.com/microsoft/TypeScript/issues/9944
  [index: string]: typeof A | number;
} = {
  A: A,
  B: 2,
  C: 3,
};
export default theExport;

我的问题是:

这个问题与以下类似但不同:

标签: typescripttype-declaration

解决方案


它不是那么漂亮,但这是一个微创更改,似乎可以在沙箱中工作:

const theExport = {
  A: A as {[K in keyof typeof A]: typeof A[K]},
  B: 2,
  C: 3
};

推荐阅读