Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exported variable X has or is using name Y from external module Z but cannot be named

I get the following error in this case using TS 3.9 with { compilerOptions: {declaration: true }} in my tsconfig.json:

// 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)

In a comment on a related issue the PM of TS at the time suggested two workarounds:

  1. explicitly import the type
  2. explicitly declare the type of the export (where the error occurs)

(1) does not work in this case. I tried exporting everything from 'a' and importing everything in 'b' and there was no difference to the error message.

The only thing that worked was this very verbose and hard to maintain explicit type annotation:

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

My question is:

  • what is a workaround I can use that doesn't involve repeating the shape of the object?
  • why does importing the type not fix the problem?

This question is similar but distinct from:

  • https://stackoverflow.com/a/44066867/2482570: not relevant because it says the problem was fixed in TS 2.9
  • https://stackoverflow.com/a/49841010/2482570: none of the answers provide a workaround that is applicable to this case
  • Typescript error: "Return type of exported function has or is using name <n> from external module <M> but cannot be named" and Typing error "Default export of the module has or is using private name" - switch from typescript v1.8 to 2: none of the solutions provided work in this case
like image 319
Max Heiber Avatar asked Jun 23 '20 15:06

Max Heiber


1 Answers

It's not that pretty, but this is a minimally invasive change that seems to work in a sandbox:

const theExport = {
  A: A as {[K in keyof typeof A]: typeof A[K]},
  B: 2,
  C: 3
};
like image 85
lazytype Avatar answered Sep 18 '22 19:09

lazytype