Home > Back-end >  Export symbols in same namespace from a multiple files in Typescript
Export symbols in same namespace from a multiple files in Typescript

Time:12-20

I have a typescript module, and want to define symbols in namespace 'aaa' from multiple files.

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";

In the second line of index.ts, I get the following warning:

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

How does one define symbols in the same namespace across multiple files, and them export them all under index.ts ?`

CodePudding user response:

You can merge the modules and their unique aaa namespaces with 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

However note the spread syntax is a shallow merge, so any conflicting declarations between a.ts and b.ts will instead opt to take b.ts's declaration.

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'
  • Related