导出的变量 X 具有或正在使用来自外部模块 Z 的名称 Y 但无法命名

Max*_*ber 7 type-declaration typescript

在这种情况下{ 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
Run Code Online (Sandbox Code Playgroud)
// Exported variable 'theExport' has or is using name 'key' from external module "c:/tsexample/src/a" but cannot be named.ts(4023)
Run Code Online (Sandbox Code Playgroud)

对相关问题评论中,当时 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;
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  • 我可以使用的不涉及重复对象形状的解决方法是什么?
  • 为什么导入类型不能解决问题?

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

eps*_*lon 5

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

const theExport = {
  A: A as {[K in keyof typeof A]: typeof A[K]},
  B: 2,
  C: 3
};
Run Code Online (Sandbox Code Playgroud)


Dor*_*onG 1

根据此评论,看起来一个解决方案可能是:

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

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

interface ITheExport {
  A: typeof A;
  B: number;
  C: number;
}

const theExport: ITheExport = { // strong typing the object instead of using inference
  A: A,
  B: 2,
  C: 3,
};
export default theExport
Run Code Online (Sandbox Code Playgroud)

参见沙箱