npm 从Typescript中的多个文件导出同一命名空间中的符号

ukdjmx9f  于 2022-12-19  发布在  TypeScript
关注(0)|答案(1)|浏览(201)

我有一个typescript模块,想从多个文件中定义名称空间“aaa”中的符号。
a.ts:

export namespace aaa {
  export const a = "a";
}

b.ts:

export namespace aaa {
  export const b = "b";
}

index.ts:

export * from "./a";
export * from "./b";

在index.ts的第二行,我得到了以下警告:

TS2308: Module "./b" has already exported a member named 'aaa'. Consider 
explicitly re-exporting to resolve the ambiguity.

如何在多个文件中定义同一名称空间中的符号,并将它们导出到index.ts下?

vuktfyat

vuktfyat1#

您可以将模块及其唯一的aaa名称空间与spread syntax合并。
index.ts

import * as A from "./a";
import * as B from "./b";
export default { ...A.aaa, ...B.aaa };

// or if you prefer a named export
export const aaa = { ...A.aaa, ...B.aaa };

someotherfile.ts

import aaa from "aaa"

const A = aaa.A

然而,注意扩展语法是浅合并,因此a.tsb.ts之间的任何冲突声明将改为选择采用b.ts的声明。
a.ts

export namespace aaa {
  export const foo = "foo";
}

b.ts

export namespace aaa {
  export const foo = "bar";
}
  • someotherfile.ts
import aaa from "aaa"

const A = aaa.foo

console.log(A) // -> 'bar'

相关问题